-
Notifications
You must be signed in to change notification settings - Fork 1
HW01. CLI. Громов Павел #1
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
PaGr0m
wants to merge
11
commits into
master
Choose a base branch
from
dev
base: master
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.
Open
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
e1de01a
Rework wc command. Rework shell. Add pipes command.
PaGr0m 4c46e14
Complete commands. Add tests
PaGr0m 9c74b3f
Add tests.
PaGr0m e32c43c
Gradle settings.
PaGr0m 9ff5e53
Rework parser
PaGr0m 58e4a69
Rework parser and substitutor. Rework Command interface. Fix pipe com…
PaGr0m 2977d2a
Complete task 1 (shell)
PaGr0m d926926
Add class diagram
PaGr0m c8b412c
Merge pull request #5 from PaGr0m/feature/dev
PaGr0m 03e2db5
Rework cat command
PaGr0m 16add6b
Create readme file
PaGr0m 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,26 @@ | ||
| # CLI | ||
|
|
||
| Данный проект - это интерпретатор командной строки, поддерживающий следующие команды: | ||
| - `cat [FILE]` - вывести на экран содержимое файла; | ||
| - `echo` - вывести на экран свой аргумент (или аргументы); | ||
| - `wc [FILE]` - вывести количество строк, слов и байт в файле; | ||
| - `pwd` - распечатать текущую директорию; | ||
| - `exit` - выйти из интерпретатора. | ||
|
|
||
| Интерпретатор распознает строку при помощи парсера, который разделяет текст на | ||
| лексемы ([`Lexemes`](https://github.com/PaGr0m/ifmo-software-design/blob/master/shell/src/main/java/parser/LexemType.java)), | ||
| которые поддерживают одинарные и двойные кавычки, а также оператор подстановки переменных окружения (`$`). | ||
|
|
||
| Все остальные команды, которые не перечислены в задании ("внешние команды") вызываются из Shell системы. | ||
|
|
||
| У `CLI` имеется свое окружение ([`Environment`](https://github.com/PaGr0m/ifmo-software-design/blob/master/shell/src/main/java/service/Environment.java)), | ||
| которое хранит в себе все переменные окружения, а также доступные команды. | ||
| Окружение является единственным для всего проекта. | ||
| Было принято решение избавиться от шаблона одиночки ([`Singleton`](https://refactoring.guru/ru/design-patterns/singleton)) | ||
| для него, а использовать внедрение зависимостей ([`Dependency Injection`](https://en.wikipedia.org/wiki/Dependency_injection#:~:text=In%20software%20engineering%2C%20dependency%20injection,object%20is%20called%20a%20service.)). | ||
|
|
||
| Для имплементации команд CLI было решено использовать паттерн "Команда" ([`Command`](https://refactoring.guru/ru/design-patterns/command)), | ||
| так как очень удобно задать единый интерфейс для функционала команды и реализовать метод для каждой команды. | ||
| Для создания команд отказался от использования шаблона "Фабрика" ([`Factory Method`](https://refactoring.guru/ru/design-patterns/factory-method)), | ||
| так как в данном случае посчитал это излишнем, поскольку обращение в `HashMap` будет намного быстрее и | ||
| по названию команды можно выдавать объект (в данном случае масштабируемость шаблона "Фабрика" никак не использовалась бы). |
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,29 @@ | ||
| plugins { | ||
| id 'java' | ||
| } | ||
|
|
||
| group 'org.jetbrains' | ||
| version '1.0-SNAPSHOT' | ||
|
|
||
| sourceCompatibility = 1.8 | ||
|
|
||
| repositories { | ||
| mavenCentral() | ||
| jcenter() | ||
| } | ||
|
|
||
| dependencies { | ||
| implementation 'org.jetbrains:annotations:15.0' | ||
|
|
||
| compile group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.13.0' | ||
| compile group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.13.0' | ||
|
|
||
| compileOnly 'org.projectlombok:lombok:1.18.12' | ||
| annotationProcessor 'org.projectlombok:lombok:1.18.12' | ||
|
|
||
| testCompileOnly 'org.projectlombok:lombok:1.18.12' | ||
| testCompile group: 'junit', name: 'junit', version: '4.12' | ||
| testCompile "org.mockito:mockito-core:2.+" | ||
| testCompile "org.assertj:assertj-core:3.11.1" | ||
| testAnnotationProcessor 'org.projectlombok:lombok:1.18.12' | ||
| } |
This file was deleted.
Oops, something went wrong.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
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,8 @@ | ||
| ## This file must *NOT* be checked into Version Control Systems, | ||
| # as it contains information specific to your local configuration. | ||
| # | ||
| # Location of the SDK. This is only used by Gradle. | ||
| # For customization when using a Version Control System, please read the | ||
| # header note. | ||
| #Mon Mar 02 23:59:06 MSK 2020 | ||
| sdk.dir=/home/pagrom/Android/Sdk |
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,2 @@ | ||
| rootProject.name = 'shell' | ||
|
|
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,2 @@ | ||
| <?xml version="1.0" encoding="UTF-8"?> | ||
| <module external.root.project.path="$MODULE_DIR$" external.system.id="GRADLE" type="JAVA_MODULE" version="4" /> |
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 |
|---|---|---|
| @@ -1,8 +1,10 @@ | ||
| import service.Shell; | ||
|
|
||
| /** | ||
| * Shell application | ||
| */ | ||
| public class Application { | ||
|
|
||
| public static void main(String[] args) { | ||
| new Shell().run(); | ||
| Shell.run(); | ||
| } | ||
| } |
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 |
|---|---|---|
| @@ -1,9 +1,20 @@ | ||
| package commands; | ||
|
|
||
| public interface Command { | ||
| String name(); | ||
| import org.jetbrains.annotations.NotNull; | ||
|
|
||
| import java.util.List; | ||
| import java.util.stream.Collectors; | ||
|
|
||
| String run(String arguments, String options); | ||
| /** | ||
| * Интерфейс для команды | ||
| */ | ||
| public interface Command { | ||
| String run(List<String> arguments); | ||
|
|
||
| void setName(String name); | ||
| default String joinArguments(@NotNull List<String> arguments) { | ||
| return arguments.stream() | ||
| .filter(str -> !str.equals("")) | ||
| .map(String::trim) | ||
| .collect(Collectors.joining(" ")); | ||
| } | ||
| } | ||
Oops, something went wrong.
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.
В целом, выделение команд в отдельную иерархию/использование паттерна команда (надеюсь, осознанное) здесь весьма разумно.
Но стоит подумать о том, действительно ли мы хотим из команд возвращать
String, потому что это накладывает сильное ограничение: нельзя вернуть из команды частичный результат. Как следствие мы не можем одновременно выполнять команды в пайпе, всем последующим командам необходимо ждать, пока предыдущая полностью завершит работу.Мб, сейчас это не самая большая проблема, но, конечно, на файлах >1гб проблема становится более очевидной.
Uh oh!
There was an error while loading. Please reload this page.
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.
Все-таки
pipesнемного иначе реализовал, а в команду передаю только аргументы