-
Notifications
You must be signed in to change notification settings - Fork 119
CLI -e / -eval — исполнение кода из строки #1724
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
yukon39
wants to merge
1
commit into
EvilBeaver:develop
Choose a base branch
from
yukon39:feature/1723-cli-eval
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+164
−0
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,75 @@ | ||
| /*---------------------------------------------------------- | ||
| This Source Code Form is subject to the terms of the | ||
| Mozilla Public License, v.2.0. If a copy of the MPL | ||
| was not distributed with this file, You can obtain one | ||
| at http://mozilla.org/MPL/2.0/. | ||
| ----------------------------------------------------------*/ | ||
| using System; | ||
| using System.IO; | ||
| using OneScript.StandardLibrary; | ||
| using ScriptEngine; | ||
| using ScriptEngine.HostedScript; | ||
| using ScriptEngine.Hosting; | ||
| using ScriptEngine.Machine; | ||
|
|
||
| namespace oscript | ||
| { | ||
| internal class ExecuteCodeBehavior(string code, string[] args) : AppBehavior, IHostApplication, ISystemLogWriter | ||
| { | ||
| private readonly string _code = code; | ||
| private readonly string[] _scriptArgs = args; | ||
|
|
||
| public static AppBehavior Create(CmdLineHelper helper) | ||
| { | ||
| var code = helper.Next(); | ||
| if (string.IsNullOrEmpty(code)) | ||
| return null; | ||
|
|
||
| return new ExecuteCodeBehavior(code, helper.Tail()); | ||
| } | ||
|
|
||
| public override int Execute() | ||
| { | ||
| SystemLogger.SetWriter(this); | ||
|
|
||
| var configPath = Path.Combine(Environment.CurrentDirectory, CfgFileConfigProvider.CONFIG_FILE_NAME); | ||
| var builder = ConsoleHostBuilder.Create(configPath); | ||
| var hostedScript = ConsoleHostBuilder.Build(builder); | ||
| var source = hostedScript.Loader.FromString(_code); | ||
|
|
||
| Process process; | ||
| try | ||
| { | ||
| process = hostedScript.CreateProcess(this, source); | ||
| } | ||
| catch (Exception e) | ||
| { | ||
| ShowExceptionInfo(e); | ||
| return 1; | ||
| } | ||
|
|
||
| var result = process.Start(); | ||
| hostedScript.Dispose(); | ||
| return result; | ||
| } | ||
|
|
||
| #region IHostApplication Members | ||
|
|
||
| public void Echo(string text, MessageStatusEnum status = MessageStatusEnum.Ordinary) | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Это начинает дублироваться с ExecuteScriptBehavior, кажется, что надо реализацию хоста вынести уже в отдельный класс |
||
| => ConsoleHostImpl.Echo(text, status); | ||
|
|
||
| public void ShowExceptionInfo(Exception exc) | ||
| => ConsoleHostImpl.ShowExceptionInfo(exc); | ||
|
|
||
| public bool InputString(out string result, string prompt, int maxLen, bool multiline) | ||
| => ConsoleHostImpl.InputString(out result, prompt, maxLen, multiline); | ||
|
|
||
| public string[] GetCommandLineArguments() | ||
| => _scriptArgs; | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Аргументы в -c/-e режиме нужны ли? |
||
|
|
||
| #endregion | ||
|
|
||
| public void Write(string text) | ||
| => Console.Error.WriteLine(text); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,83 @@ | ||
| Перем юТест; | ||
|
|
||
| Функция ПолучитьСписокТестов(ЮнитТестирование) Экспорт | ||
|
|
||
| юТест = ЮнитТестирование; | ||
|
|
||
| ВсеТесты = Новый Массив; | ||
| ВсеТесты.Добавить("ТестДолжен_ВыполнитьКодЧерезФлагE"); | ||
| ВсеТесты.Добавить("ТестДолжен_ВыполнитьКодЧерезФлагEval"); | ||
| ВсеТесты.Добавить("ТестДолжен_ПередатьАргументыПослеКода"); | ||
| ВсеТесты.Добавить("ТестДолжен_ПоказатьUsageЕслиНетКода"); | ||
| ВсеТесты.Добавить("ТестДолжен_РаботатьСEncoding"); | ||
|
|
||
| Возврат ВсеТесты; | ||
|
|
||
| КонецФункции | ||
|
|
||
| Функция ПутьОСкрипт() | ||
| Возврат "dotnet """ + ОбъединитьПути(КаталогПрограммы(), "oscript.dll") + """"; | ||
| КонецФункции | ||
|
|
||
| Функция НормализоватьВывод(Знач Текст) | ||
| Текст = СтрЗаменить(Текст, Символы.ВК, ""); | ||
| Возврат СокрЛП(Текст); | ||
| КонецФункции | ||
|
|
||
| Функция ЗапуститьОскрипт(Знач Аргументы) | ||
|
|
||
| Процесс = СоздатьПроцесс(ПутьОСкрипт() + " " + Аргументы, , Истина, , КодировкаТекста.UTF8); | ||
| Процесс.Запустить(); | ||
| Процесс.ОжидатьЗавершения(); | ||
|
|
||
| Результат = Новый Структура; | ||
| Результат.Вставить("КодВозврата", Процесс.КодВозврата); | ||
| Результат.Вставить("Вывод", НормализоватьВывод(Процесс.ПотокВывода.Прочитать())); | ||
| Возврат Результат; | ||
|
|
||
| КонецФункции | ||
|
|
||
| Процедура ТестДолжен_ВыполнитьКодЧерезФлагE() Экспорт | ||
|
|
||
| Результат = ЗапуститьОскрипт("-e ""Сообщить(1+2)"""); | ||
|
|
||
| юТест.ПроверитьРавенство(0, Результат.КодВозврата, "Код возврата"); | ||
| юТест.ПроверитьРавенство("3", Результат.Вывод, "Вывод выражения"); | ||
|
|
||
| КонецПроцедуры | ||
|
|
||
| Процедура ТестДолжен_ВыполнитьКодЧерезФлагEval() Экспорт | ||
|
|
||
| Результат = ЗапуститьОскрипт("-eval ""Сообщить(1+2)"""); | ||
|
|
||
| юТест.ПроверитьРавенство(0, Результат.КодВозврата, "Код возврата"); | ||
| юТест.ПроверитьРавенство("3", Результат.Вывод, "Вывод выражения"); | ||
|
|
||
| КонецПроцедуры | ||
|
|
||
| Процедура ТестДолжен_ПередатьАргументыПослеКода() Экспорт | ||
|
|
||
| Результат = ЗапуститьОскрипт("-e ""Сообщить(АргументыКоманднойСтроки[0])"" hello"); | ||
|
|
||
| юТест.ПроверитьРавенство(0, Результат.КодВозврата, "Код возврата"); | ||
| юТест.ПроверитьРавенство("hello", Результат.Вывод, "Аргумент скрипта"); | ||
|
|
||
| КонецПроцедуры | ||
|
|
||
| Процедура ТестДолжен_ПоказатьUsageЕслиНетКода() Экспорт | ||
|
|
||
| Результат = ЗапуститьОскрипт("-e"); | ||
|
|
||
| юТест.ПроверитьРавенство(0, Результат.КодВозврата, "Код возврата usage"); | ||
| юТест.ПроверитьИстину(СтрНайти(Результат.Вывод, "-eval, -e") > 0, "В usage должен быть флаг -eval, -e"); | ||
|
|
||
| КонецПроцедуры | ||
|
|
||
| Процедура ТестДолжен_РаботатьСEncoding() Экспорт | ||
|
|
||
| Результат = ЗапуститьОскрипт("-encoding=utf-8 -e ""Сообщить(""""привет"""")"""); | ||
|
|
||
| юТест.ПроверитьРавенство(0, Результат.КодВозврата, "Код возврата"); | ||
| юТест.ПроверитьРавенство("привет", Результат.Вывод, "Вывод с -encoding"); | ||
|
|
||
| КонецПроцедуры |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Непонятно, что такое args в случае команды eval?