Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/oscript/BehaviorSelector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ private static AppBehavior SelectParametrized(CmdLineHelper helper)
initializers.Add("-cgi", h => new CgiBehavior());
initializers.Add("-version", h => new ShowVersionBehavior());
initializers.Add("-v", h => new ShowVersionBehavior());
initializers.Add("-e", ExecuteCodeBehavior.Create);
initializers.Add("-eval", ExecuteCodeBehavior.Create);
initializers.Add("-encoding", ProcessEncodingKey);
initializers.Add("-codestat", EnableCodeStatistics);
initializers.Add("-debug", DebugBehavior.Create);
Expand Down
75 changes: 75 additions & 0 deletions src/oscript/ExecuteCodeBehavior.cs
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;

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Непонятно, что такое args в случае команды eval?


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)

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The 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;

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Аргументы в -c/-e режиме нужны ли?


#endregion

public void Write(string text)
=> Console.Error.WriteLine(text);
}
}
2 changes: 2 additions & 0 deletions src/oscript/ShowUsageBehavior.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ public override int Execute()
Output.WriteLine();
Output.WriteLine("Usage:");
Output.WriteLine(" oscript.exe [options] <script_path> [script_arguments...]");
Output.WriteLine(" oscript.exe [options] -e <code> [script_arguments...]");
Output.WriteLine(" oscript.exe <mode> [mode_options] <script_path> [script_arguments...]");
Output.WriteLine();

Expand All @@ -34,6 +35,7 @@ public override int Execute()
Output.WriteLine($" {"",modeWidth} {"-port=<port>",subOptionWidth} Debugger port (default is 2801).");
Output.WriteLine($" {"",modeWidth} {"-noWait",subOptionWidth} Do not wait for debugger connection.");

Output.WriteLine($" {"-eval, -e",modeWidth} Execute code from command line.");
Output.WriteLine($" {"-version, -v",modeWidth} Output version string.");
Output.WriteLine();

Expand Down
83 changes: 83 additions & 0 deletions tests/cli-eval.os
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");

КонецПроцедуры
2 changes: 2 additions & 0 deletions tests/process.os
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@
|
|Usage:
| oscript.exe [options] <script_path> [script_arguments...]
| oscript.exe [options] -e <code> [script_arguments...]
| oscript.exe <mode> [mode_options] <script_path> [script_arguments...]
|
|Modes:
Expand All @@ -158,6 +159,7 @@
| Options:
| -port=<port> Debugger port (default is 2801).
| -noWait Do not wait for debugger connection.
| -eval, -e Execute code from command line.
| -version, -v Output version string.
|
|Options:
Expand Down