Skip to content
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

Муканов Арман #203

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
19 changes: 19 additions & 0 deletions ConsoleApp/CommandLineParsers/Handlers/ExitOptionsHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using ConsoleApp.CommandLineParsers.Options;

namespace ConsoleApp.CommandLineParsers.Handlers;

public class ExitOptionsHandler: IOptionsHandler<ExitOptions>
{
public void Map(ExitOptions options)
{
}

public void Map(object options)
{
}

public void Execute()
{
Environment.Exit(0);
}
}
15 changes: 15 additions & 0 deletions ConsoleApp/CommandLineParsers/Handlers/IOptionsHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using ConsoleApp.CommandLineParsers.Options;

namespace ConsoleApp.CommandLineParsers.Handlers;

public interface IOptionsHandler<in TOptions> : IOptionsHandler where TOptions : IOptions
{
public void Map(TOptions options);

Choose a reason for hiding this comment

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

так, давай рассказывай почему везде используешь грязные методы и все взаимодействие происходит через изменения состояния каких то других контрактов?
а так же давай подумаем почему это плохо, потому что это не первый раз встречается в твоем коде

чем это все отличается от вот такого интерфейса? (сейчас все интерфейсы у тебя по сути можно заменить на этот)

public inteface IDoEverything
{
    void Do();
}

}

public interface IOptionsHandler
{
public void Map(object options);

public void Execute();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
using ConsoleApp.CommandLineParsers.Options;
using MyStemWrapper;
using TagsCloudContainer;
using TagsCloudContainer.Settings;
using TagsCloudContainer.TextAnalysers;

namespace ConsoleApp.CommandLineParsers.Handlers;

public class PreprocessTextOptionsHandler: IOptionsHandler<PreprocessTextOptions>
{
private readonly ITextPreprocessor textPreprocessor;
private readonly FileReader fileReader;
private readonly CloudData cloudData;
private readonly MyStem myStem;

public PreprocessTextOptionsHandler(ITextPreprocessor textPreprocessor, FileReader fileReader, CloudData cloudData, MyStem myStem)
{
this.textPreprocessor = textPreprocessor;
this.fileReader = fileReader;
this.cloudData = cloudData;
this.myStem = myStem;
}

public void Map(PreprocessTextOptions options)
{
cloudData.FilePath = options.FilePath;
if (options.Parameters is not null)
myStem.Parameters = "-" + options.Parameters;
}

public void Map(object options)
{
if (options is PreprocessTextOptions opts)
Map(opts);
else
throw new ArgumentException(nameof(options));
}

public void Execute()
{
var text = fileReader.ReadFile();
textPreprocessor.Preprocess(text);
}
}
46 changes: 46 additions & 0 deletions ConsoleApp/CommandLineParsers/Handlers/SaveImageOptionsHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
using System.Drawing;
using ConsoleApp.CommandLineParsers.Options;
using TagsCloudContainer.Settings;
using TagsCloudContainer.Visualizers;

namespace ConsoleApp.CommandLineParsers.Handlers;

public class SaveImageOptionsHandler : IOptionsHandler<SaveImageOptions>
{
private readonly ImageSettings imageSettings;
private readonly ICloudVisualizer visualizer;


public SaveImageOptionsHandler(ImageSettings imageSettings, ICloudVisualizer visualizer)
{
this.imageSettings = imageSettings;
this.visualizer = visualizer;
}

public void Map(SaveImageOptions options)
{
if (options.PrimaryColor != default)
imageSettings.PrimaryColor = options.PrimaryColor;
if (options.BackgroundColor != default)
imageSettings.BackgroundColor = options.BackgroundColor;
if (options.Width != default && options.Height != default)
imageSettings.ImageSize = new Size(options.Width, options.Height);
if (options.Font is not null)
imageSettings.Font = options.Font;
imageSettings.File = options.FilePath;
}

public void Map(object options)
{
if (options is SaveImageOptions opts)
Map(opts);
else
throw new ArgumentException();
}

public void Execute()
{
visualizer.GenerateImage();
visualizer.SaveImage();
}
}
8 changes: 8 additions & 0 deletions ConsoleApp/CommandLineParsers/Options/ExitOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
using CommandLine;

namespace ConsoleApp.CommandLineParsers.Options;

[Verb("exit", HelpText = "Закончить выполнение программы")]
public class ExitOptions: IOptions
{
}
5 changes: 5 additions & 0 deletions ConsoleApp/CommandLineParsers/Options/IOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
namespace ConsoleApp.CommandLineParsers.Options;

public interface IOptions
{
}
13 changes: 13 additions & 0 deletions ConsoleApp/CommandLineParsers/Options/PreprocessTextOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using CommandLine;

namespace ConsoleApp.CommandLineParsers.Options;

[Verb("generate", HelpText = "Предобработка слов")]
public class PreprocessTextOptions: IOptions
{
[Option('f', "file", Required = true)]
public string FilePath { get; set; }

[Option('p', "params")]
public string Parameters { get; set; }
}
29 changes: 29 additions & 0 deletions ConsoleApp/CommandLineParsers/Options/SaveImageOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
using System.Drawing;
using CommandLine;

namespace ConsoleApp.CommandLineParsers.Options;

[Verb("image", HelpText = "Настройка изображения")]
public class SaveImageOptions: IOptions
{
[Option('c', "color")]
public Color PrimaryColor { get; set; }

[Option('s', "secondcolor")]
public Color SecondaryColor { get; set; }

[Option('b', "background")]
public Color BackgroundColor { get; set; }

[Option('p', "path", Required = true)]
public string FilePath { get; set; }

[Option('w', "width")]
public int Width { get; set; }

[Option('h', "height")]
public int Height { get; set; }

[Option('f', "font")]
public Font Font { get; set; }
}
52 changes: 52 additions & 0 deletions ConsoleApp/CommandLineReader.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
using CommandLine;
using ConsoleApp.CommandLineParsers.Handlers;
using ConsoleApp.CommandLineParsers.Options;

namespace ConsoleApp;

public class CommandLineReader
{
private readonly IOptionsHandler[] handlers;

public CommandLineReader(IOptionsHandler[] handlers)
{
this.handlers = handlers;
}

public void Read()
{
while (true)
{
var input = Console.ReadLine();
var args = input.Split();

Parser.Default.ParseArguments<PreprocessTextOptions, SaveImageOptions, ExitOptions>(args)
.WithParsed<PreprocessTextOptions>(opt =>
{
var handler = handlers.FirstOrDefault(h => h is IOptionsHandler<PreprocessTextOptions>);
if (handler is null)
throw new Exception("Обработчик параметров не найден.");

handler.Map(opt);
handler.Execute();
})
.WithParsed<SaveImageOptions>(opt =>
{
var handler = handlers.FirstOrDefault(h => h is IOptionsHandler<SaveImageOptions>);
if (handler is null)
throw new Exception("Обработчик параметров не найден.");

handler.Map(opt);
handler.Execute();
})
.WithParsed<ExitOptions>(opt =>
{
var handler = handlers.FirstOrDefault(h => h is IOptionsHandler<ExitOptions>);
if (handler is null)
throw new Exception("Обработчик параметров не найден.");

handler.Execute();
});
}
}
}
18 changes: 18 additions & 0 deletions ConsoleApp/ConsoleApp.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">

Choose a reason for hiding this comment

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

хорошо что выделил в отдельную сборку CUI


<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\TagsCloudContainer\TagsCloudContainer.csproj" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Autofac" Version="8.0.0" />
</ItemGroup>

</Project>
66 changes: 66 additions & 0 deletions ConsoleApp/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
using System.Reflection;
using Autofac;
using CommandLine;
using ConsoleApp;
using ConsoleApp.CommandLineParsers.Handlers;
using ConsoleApp.CommandLineParsers.Options;
using MyStemWrapper;
using TagsCloudContainer;
using TagsCloudContainer.CloudLayouters;
using TagsCloudContainer.Settings;
using TagsCloudContainer.TextAnalysers;
using TagsCloudContainer.Visualizers;

internal class Program
{
public static void Main(string[] args)

Choose a reason for hiding this comment

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

если ты создаешь CUI то позаботься о том чтобы пользователь мог пользоваться твоей тулзой, если она запускается с какими то аргументами то должна быть осмысленная исчерпывающая подсказка по этим аргументам, если ты делаешь некое подобие shell то подсказка так же обязана быть, смотри туториалы по CommanLineParser, там все это доступно из коробки

сейчас без чтения кода вообще нет никакого понимания как пользоваться такой тулзой

{
var builder = new ContainerBuilder();
ConfigureService(builder);
var container = builder.Build();

using var scope = container.BeginLifetimeScope();
var commandLineReader = scope.Resolve<CommandLineReader>();
while (true)
{
commandLineReader.Read();
}
}

private static void ConfigureService(ContainerBuilder builder)
{
builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies())
.Where(t => typeof(IOptions).IsAssignableFrom(t))
.AsImplementedInterfaces();

builder.RegisterType<PreprocessTextOptionsHandler>().As<IOptionsHandler<PreprocessTextOptions>, IOptionsHandler>();
builder.RegisterType<SaveImageOptionsHandler>().As<IOptionsHandler<SaveImageOptions>, IOptionsHandler>();
builder.RegisterType<ExitOptionsHandler>().As<IOptionsHandler<ExitOptions>, IOptionsHandler>();
builder.RegisterType<CommandLineReader>().AsSelf();

var location = Assembly.GetExecutingAssembly().Location;
var path = Path.GetDirectoryName(location);
var myStem = new MyStem
{
PathToMyStem =
$"{path}\\mystem.exe",
Parameters = "-nli"
};
builder.RegisterInstance(myStem).AsSelf().SingleInstance();

builder.RegisterType<CloudData>().AsSelf().SingleInstance();
builder.RegisterType<ImageSettings>().AsSelf().SingleInstance();
builder.RegisterType<AnalyseSettings>().AsSelf().SingleInstance();

builder.RegisterType<TextPreprocessor>().As<ITextPreprocessor>();
builder.RegisterType<FileReader>().AsSelf();


builder.RegisterType<TagsCloudGenerator>().As<ITagsCloudGenerator>();
builder.RegisterType<CircularCloudLayouter>().As<ICloudLayouter>();


builder.RegisterType<CloudVisualizer>().As<ICloudVisualizer>();
builder.RegisterType<FontSizeProvider>().AsSelf();
}
}
1 change: 1 addition & 0 deletions TagsCloudContainer.Tests/GlobalUsings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
global using NUnit.Framework;
20 changes: 20 additions & 0 deletions TagsCloudContainer.Tests/TagsCloudContainer.Tests.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.7.1"/>
<PackageReference Include="NUnit" Version="3.13.3"/>
<PackageReference Include="NUnit3TestAdapter" Version="4.4.2"/>
<PackageReference Include="NUnit.Analyzers" Version="3.6.1"/>
<PackageReference Include="coverlet.collector" Version="3.2.0"/>
</ItemGroup>

</Project>
15 changes: 15 additions & 0 deletions TagsCloudContainer.Tests/TagsCloudGeneratorTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
namespace TagsCloudContainer.Tests;

public class TagsCloudGeneratorTests

Choose a reason for hiding this comment

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

у тебя же должны были остаться тесты после предыдущего блока с генератором облака, почему хотя бы те тесты не перенес сюда?

{
[SetUp]
public void Setup()
{
}

[Test]
public void Test1()
{
Assert.Pass();
}
}
Loading