Repository navigation
Приложение для терминала #2
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
Merged
keksobot
merged 2 commits into
htmlacademy-nodejs-api:master
from
Critonik:module1-task2
Jan 9, 2026
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| Тестовое объявление об аренде Комнатка в Париже 2022-01-10T19:00:00.000Z Paris preview.jpg photo1;photo2;photo3 false true 4.6 house 1 2 100 Breakfast;Baby seat https://user 50 48.85661 2.351499 | ||
| Тестовое объявление об аренде2 Комнатка в Кёльне 2022-04-10T19:00:00.000Z Cologne preview.jpg photo1;photo2;photo3 true false 4.6 room 1 2 100 Breakfast;Baby seat https://user 33 50.938361 6.959974 |
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
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,40 @@ | ||
| import type { Command } from './commands/command.interface.js'; | ||
| import { CommandParser } from './command-parser.js'; | ||
|
|
||
| type CommandCollection = Record<string, Command>; | ||
|
|
||
| export class CLIApplication { | ||
| private commands: CommandCollection = {}; | ||
|
|
||
| constructor( | ||
| private readonly defaultCommand: string = '--help' | ||
| ) {} | ||
|
|
||
| public registerCommands(commandList: Command[]): void { | ||
| commandList.forEach((command) => { | ||
| if (Object.hasOwn(this.commands, command.getName())) { | ||
| throw new Error(`Command ${command.getName()} is already registered`); | ||
| } | ||
| this.commands[command.getName()] = command; | ||
| }); | ||
| } | ||
|
|
||
| public getCommand(commandName: string): Command { | ||
| return this.commands[commandName] ?? this.getDefaultCommand(); | ||
| } | ||
|
|
||
| public getDefaultCommand(): Command | never { | ||
| if (! this.commands[this.defaultCommand]) { | ||
| throw new Error(`The default command (${this.defaultCommand}) is not registered.`); | ||
| } | ||
| return this.commands[this.defaultCommand]; | ||
| } | ||
|
|
||
| public processCommand(argv: string[]): void { | ||
| const parsedCommand = CommandParser.parse(argv); | ||
| const [commandName] = Object.keys(parsedCommand); | ||
| const command = this.getCommand(commandName); | ||
| const commandArguments = parsedCommand[commandName] ?? []; | ||
| command.execute(...commandArguments); | ||
| } | ||
| } |
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,19 @@ | ||
| type ParsedCommand = Record<string, string[]> | ||
|
|
||
| export class CommandParser { | ||
| static parse(cliArguments: string[]): ParsedCommand { | ||
| const parsedCommand: ParsedCommand = {}; | ||
| let currentCommand = ''; | ||
|
|
||
| for (const argument of cliArguments) { | ||
| if (argument.startsWith('--')) { | ||
| parsedCommand[argument] = []; | ||
| currentCommand = argument; | ||
| } else if (currentCommand && argument) { | ||
| parsedCommand[currentCommand].push(argument); | ||
| } | ||
| } | ||
|
|
||
| return parsedCommand; | ||
| } | ||
| } |
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,4 @@ | ||
| export interface Command { | ||
| getName(): string; | ||
| execute(...params: string[]): void; | ||
| } |
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,25 @@ | ||
| import type { Command } from './command.interface.js'; | ||
| import chalk from 'chalk'; | ||
|
|
||
| export class HelpCommand implements Command { | ||
| execute(..._params: string[]): void { | ||
| console.info(chalk.bgBlackBright( | ||
| ` | ||
| Программа для подготовки данных для REST API сервера. | ||
| Пример: | ||
| cli.js --<command> [--arguments] | ||
| Команды: | ||
| --version: # выводит номер версии | ||
| --help: # печатает этот текст | ||
| --import <path>: # импортирует данные из TSV | ||
| --generate <n> <path> <url> # генерирует произвольное количество тестовых данных | ||
| ` | ||
| )); | ||
|
|
||
| } | ||
|
|
||
| getName(): string { | ||
| return '--help'; | ||
| } | ||
|
|
||
| } |
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,23 @@ | ||
| import type { Command } from './command.interface.js'; | ||
| import { TsvFileReader } from '../../shared/lib/tsv-file-reader.js'; | ||
|
|
||
| export class ImportCommand implements Command { | ||
| execute(...params: string[]): void { | ||
| const [filename] = params; | ||
| const fileReader = new TsvFileReader(filename); | ||
| try { | ||
| fileReader.read(); | ||
| console.log(fileReader.toArray()); | ||
| } catch (error) { | ||
| if (!(error instanceof Error)) { | ||
| throw error; | ||
| } | ||
| console.error(`Details ${error.message}`); | ||
| } | ||
| } | ||
|
|
||
| getName(): string { | ||
| return '--import'; | ||
| } | ||
|
|
||
| } |
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,45 @@ | ||
| import { resolve } from 'node:path'; | ||
| import type { Command } from './command.interface.js'; | ||
| import { readFileSync } from 'node:fs'; | ||
| import chalk from 'chalk'; | ||
|
|
||
| interface PackageJsonData { | ||
| version: string | ||
| } | ||
|
|
||
|
|
||
| export class VersionCommand implements Command { | ||
| constructor(private readonly filepath: string = './package.json') { | ||
| } | ||
|
|
||
| private readVersion(): string { | ||
| const json = readFileSync(resolve(this.filepath), 'utf-8'); | ||
| const parsedData: unknown = JSON.parse(json); | ||
|
|
||
| if (!this.isPackageJson(parsedData)) { | ||
| throw new Error('Invalid package.json'); | ||
| } | ||
|
|
||
| return parsedData.version; | ||
| } | ||
|
|
||
| private isPackageJson(value: unknown): value is PackageJsonData { | ||
| return value !== null && typeof value === 'object' && !Array.isArray(value) && Object.hasOwn(value, 'version'); | ||
| } | ||
|
|
||
| execute(..._params: string[]): void { | ||
| try { | ||
| const ver = this.readVersion(); | ||
| console.log(chalk.green(ver)); | ||
| } catch (e) { | ||
| console.error(`Failed to read version from ${this.filepath}`); | ||
| if (e instanceof Error) { | ||
| console.error(chalk.bgRed(e.message)); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| getName(): string { | ||
| return '--version'; | ||
| } | ||
| } | ||
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,5 @@ | ||
| export * from './cli-application.js'; | ||
| export * from './command-parser.js'; | ||
| export * from './commands/help.command.js'; | ||
| export * from './commands/version.command.js'; | ||
| export * from './commands/import.command.js'; |
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,15 @@ | ||
| #!/usr/bin/env node | ||
| import { CLIApplication, HelpCommand, ImportCommand, VersionCommand } from './cli/index.js'; | ||
|
|
||
| function bootstrap() { | ||
| const cliApplication = new CLIApplication(); | ||
| cliApplication.registerCommands([ | ||
| new HelpCommand(), | ||
| new VersionCommand(), | ||
| new ImportCommand(), | ||
| ]); | ||
|
|
||
| cliApplication.processCommand(process.argv); | ||
| } | ||
|
|
||
| bootstrap(); |
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,3 @@ | ||
| export interface FileReader { | ||
| read(): void | ||
| } |
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.
Тоже полезно знать, что функции файловой системы которые *Sync блокируют выполнение потока, то есть использовать их нужно аккуратно и тогда когда ты действительно понимаешь что это не затормозит какие то паралельные процессы.
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.
да, спасибо, тут по примеру из лекции просто синхронную функцию вызвал