Skip to content

Commit

Permalink
Update from 31
Browse files Browse the repository at this point in the history
  • Loading branch information
Administrator committed Aug 31, 2022
1 parent aa91c80 commit e42d06a
Show file tree
Hide file tree
Showing 10 changed files with 121 additions and 7,015 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ Cat is one of the most frequently used commands on Unix-like operating systems.
- The programs must be developed in C language of C11 standard using gcc compiler.
- The program code of the cat and grep must be located on the develop branch in the src/cat/ and src/grep/ folders, respectively
- Do not use outdated and legacy language constructions and library functions. Pay attention to the legacy and obsolete marks in the official documentation on the language and the libraries used. Use the POSIX.1-2017 standard.
- When writing code it is necessary to follow the Google style
- The programs must be executable files with command line arguments
- The programs must be built with Makefile with appropriate targets: s21_cat, s21_grep
- If third-party libraries are used, there must be build scripts in makefile to connect/load them
Expand Down
1 change: 1 addition & 0 deletions README_RUS.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ grep впервые был включен в Версию 4 Unix. Заявив,
- Программы должны быть разработаны на языке Си стандарта C11 с использованием компилятора gcc
- Код программ cat и grep должен находиться в ветке develop в папках src/cat/ и src/grep/ соответственно
- Не использовать устаревшие и выведенные из употребления конструкции языка и библиотечные функции. Обращать внимания на пометки legacy и obsolete в официальной документации по языку и используемым библиотекам. Ориентироваться на стандарт POSIX.1-2017
- При написании кода необходимо придерживаться Google Style
- Программы должны представлять собой исполняемый файл с аргументами командной строки
- Сборка программ должна быть настроена с помощью Makefile с соответствующими целями: s21_cat, s21_grep
- Если используются сторонние библиотеки, в Makefile должны быть заложены сценарии сборки, предусматривающие их подключение/загрузку
Expand Down
4 changes: 4 additions & 0 deletions materials/build/scripts/.clang-format
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
---
BasedOnStyle: Google
IndentWidth: 4
ColumnLimit: 110
9 changes: 0 additions & 9 deletions materials/build/scripts/CPPLINT.cfg

This file was deleted.

21 changes: 11 additions & 10 deletions materials/build/scripts/style_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import sys

PATH_TO_PROJECT = '/'.join(os.path.abspath(os.path.dirname(sys.argv[0])).split('/')[:-1])
PATH_TO_CPPLINT = PATH_TO_PROJECT + '/tests/linters/cpplint.py'

devnull_stderr = sys.stdout
devnull_stdout = sys.stdout
Expand All @@ -23,27 +22,29 @@ def get_source_filenames():
return arr_of_files


def copy_cpplint_config():
subprocess.run(['cp', PATH_TO_PROJECT + '/tests/CPPLINT.cfg', PATH_TO_PROJECT], stdout=devnull_stdout,
def copy_config():
subprocess.run(['cp', PATH_TO_PROJECT + '/tests/.clang-format', PATH_TO_PROJECT], stdout=devnull_stdout,
stderr=devnull_stderr)


def delete_cpplint_config():
subprocess.run(['rm', PATH_TO_PROJECT + '/CPPLINT.cfg'], stdout=devnull_stdout, stderr=devnull_stderr)
def delete_config():
subprocess.run(['rm', PATH_TO_PROJECT + '/.clang-format'], stdout=devnull_stdout, stderr=devnull_stderr)


def style_test_result(arr_of_files):
copy_cpplint_config()
copy_config()

for i in range(len(arr_of_files)):
result_style_test = subprocess.run(
['python3', PATH_TO_CPPLINT, '--extensions=c', '--quiet', PATH_TO_PROJECT + '/src/' + arr_of_files[i]],
stderr=devnull_stderr, stdout=subprocess.PIPE, text=True)
['clang-format', '-n', PATH_TO_PROJECT + '/src/' + arr_of_files[i]],
stderr=subprocess.STDOUT, stdout=subprocess.PIPE, text=True)

if len(result_style_test.stdout) != 0:
delete_cpplint_config()
print(result_style_test.stdout)
delete_config()
return False

delete_cpplint_config()
delete_config()

return True

Expand Down
96 changes: 50 additions & 46 deletions materials/instructions_for_testing.md
Original file line number Diff line number Diff line change
@@ -1,46 +1,50 @@
# Instructions for running tests.

In addition to testing for correct output data, the autotest system will
check your program and its source code for the following points:

* **Style tests.** To check how much the beauty of your code matches
for example, you can test your code using the script ```materials/linters/cpplint.py```.
The ```materials/linters``` folder also contains the ```CPPLINT.cfg``` file, which contains
the necessary filters-settings for the style test. The script works in such a way that this
configuration file extends its action to all files that lie with it in the directory
or in the directories below. So in order for these settings to apply to your source code files,
copy ```CPPLINT. cfg``` to the ```src``` folder. \
\
To run the script, run the following command: \
```python3 materials/linters/cpplint.py --extensions=c src/sourcefile_name.c``` \
\
Important! To run, you need python version 3. Check the installed version on
you can download the version using the command ```python3 --version```.
To download python3, enter one of the following commands in the terminal: \
```brew install python3``` \
or if you have root rights (for Ubuntu / Linux Mint / Debian) \
```sudo apt install python3```


* **Test for correct operation with memory.** When writing C programs, it is very important to watch for memory leaks. To do this the _valgrind_ utility is quite often used in Unix-like operating systems. However OS X has some troubles with valgrind support, so it is possible to use _leaks_ utility instead. Go into we will not discuss the mechanism of their operation now - if you are interested, you can read about it on Google.

To run your executable file using this utility, type in the terminal: \
```leaks -atExit -- ./main.out | grep LEAK:```

Pay your attention that there is ```| grep LEAK:``` command. We use it to short leaks output to see only lines with leaks if they are there. If you want to see the whole output, just remove this command.

When you run your executable file using _leaks_ you may see an error:
>dyld: could not load inserted library ‘/usr/local/lib/libLeaksAtExit.dylib’ because image not found
It’s because _leaks_ did not find _libLeaksAtExit.dylib_ library. \
You need to type the following commands in this case.
```sh
cd /usr/local/lib
sudo ln -s /Applications/Xcode.app/Contents/Developer/usr/lib/libLeaksAtExit.dylib
```

_Additionally:_ \
Use the ```-exclude``` option of _leaks_ to filter out leaks in functions with known memory leaks.
This option helps reduce the amount of extra information reported by _leaks_.

* **Build test** The program can be checked for correct build on a test system enviroment. This will require Docker installed. If the system has a docker, then you can go to the materials / build directory and run the run.sh script from there. The script will wrap your solution in docker and run it along with a typical build script.
# Instructions for running tests.

In addition to testing for correct output data, the autotest system will check your program and its source code for the
following points:

* **Style tests.** To check how much the beauty of your code meets the standards, for example, you can test your code
using the _clang-format_ utility. The ```materials/linters``` folder contains the ```.clang-format``` file, which
contains the necessary settings for the style test. This configuration file extends its action to all files that lie
with it in the directory or in the directories below. So in order for these settings to apply to your source code
files, copy ```.clang-format``` to the ```src``` folder. \
\
To run the style check, run the following command: \
```clang-format -n src/sourcefile_name.c``` \
\
To download _clang-format_, enter one of the following commands in the terminal: \
```brew install clang-format``` \
or if you have root rights (for Ubuntu / Linux Mint / Debian) \
```sudo apt install clang-format```

Google Style: https://google.github.io/styleguide/cppguide.html


* **Test for correct operation with memory.** When writing C programs, it is very important to watch for memory leaks.
To do this the _valgrind_ utility is quite often used in Unix-like operating systems. However, OS X has some troubles
with _valgrind_ support, so it is possible to use the _leaks_ utility instead. We will not go into the mechanism of
operation of these utilities now — if you are interested, you can read about it on Google.

To run your executable file using this utility, type in the terminal: \
```leaks -atExit -- ./main.out | grep LEAK:```

Pay your attention that there is ```| grep LEAK:``` command. We use it to short leaks output to see only lines with
leaks if they are there. If you want to see the whole output, just remove this command.

When you run your executable file using _leaks_ you may see an error:
> dyld: could not load inserted library ‘/usr/local/lib/libLeaksAtExit.dylib’ because image not found
It’s because _leaks_ did not find _libLeaksAtExit.dylib_ library. \
You need to type the following commands in this case.
```sh
cd /usr/local/lib
sudo ln -s /Applications/Xcode.app/Contents/Developer/usr/lib/libLeaksAtExit.dylib
```

_Additionally:_ \
Use the ```-exclude``` option of _leaks_ to filter out leaks in functions with known memory leaks. This option helps
reduce the amount of extra information reported by _leaks_.

* **Build test.** The program can be checked for correct build on a test system environment. This will require _Docker_
installed. If the system has a docker, then you can go to the `materials/build` directory and run the run.sh script
from there. The script will wrap your solution in docker and run it along with a typical build script.
90 changes: 50 additions & 40 deletions materials/instructions_for_testing_rus.md
Original file line number Diff line number Diff line change
@@ -1,40 +1,50 @@
# Инструкция по запуску тестов.

Помимо тестов на корректные выходные данные система автотестирования будет
проверять вашу программу и ее исходный код по следующим пунктам:

* **Стилевые тесты.** Чтобы проверить, насколько красота вашего кода соответствует
стандартам, вы можете протестировать ваш код с помощью скрипта ```materials/linters/cpplint.py```. В папке ```materials/linters``` также лежит файл ```CPPLINT.cfg```, который содержит необходимые фильтры-настройки для стилевого теста. Скрипт работает таким образом, что данный конфигурационный файл распространяет свое действие на все файлы, которые лежат с ним в директории или в директориях ниже. Поэтому, чтобы данные настройки применились к вашим файлам с исходным кодом, скопируйте ```CPPLINT.cfg``` в папку src. \
\
Чтобы запустить скрипт, выполните следующую команду: \
```python3 materials/linters/cpplint.py --extensions=c src/sourcefile_name.c``` \
\
Важно! Для запуска вам необходим python версии 3. Проверить установленную на
компьютере версию можно с помощью команды ```python3 --version```
Чтобы скачать python3, введите в терминал одну из следующих команд: \
```brew install python3``` \
или, если у вас есть root-права (для Ubuntu / Linux Mint / Debian) \
```sudo apt install python3```


* **Тест на корректную работу с памятью.** При написании C-программ очень важно следить за утечками памяти. Для этого в Unix-подобных операционных системах довольно часто используют утилиту _valgrind_. Однако, на OS X имеются проблемы с поддержкой valgrind, поэтому вместо нее можно использовать утилиту _leaks_. Вдаваться в механизм работы этих утилит мы сейчас не будем - если интересно, можете почитать в гугле.

Чтобы запустить ваш исполняемый файл с помощью этой утилиты, наберите в терминале: \
```leaks -atExit -- ./main.out | grep LEAK:```

Обратите внимание на команду ```| grep LEAK:```. Мы используем ее для короткого вывода, чтобы видеть только линии с утечками, если они есть. Если вы хотите увидеть весь вывод, просто удалите эту команду.

При запуске исполняемого файла с помощью _leaks_ может появиться сообщение об ошибке:
>dyld: could not load inserted library ‘/usr/local/lib/libLeaksAtExit.dylib’ because image not found
Ошибка возникает из-за того, что _leaks_ не может найти библиотеку _libLeaksAtExit.dylib_. \
В этом случае вам необходимо ввести следующие команды:
```sh
cd /usr/local/lib
sudo ln -s /Applications/Xcode.app/Contents/Developer/usr/lib/libLeaksAtExit.dylib
```

_Дополнительно:_ \
Используйте флаг ```-exclude``` утилиты _leaks_ для того, чтобы отфильтровать утечки в функциях, где известно об утечках памяти. Этот флаг позволяет уменьшить количество посторонней информации, сообщаемой _leaks_.

* **Тест сборки** Программу можно проверить на корректность сборки на тестовой системе. Для этого потребуется установленный Docker. Если на системе есть докер, то можно зайти в директорию materials/build и запустить оттуда скрипт run.sh. Скрипт обернет ваше решение в докер и запустит его вместе с типовым сценарием сборки.
# Инструкция по запуску тестов.

Помимо тестов на корректные выходные данные система автотестирования будет проверять вашу программу и ее исходный код по
следующим пунктам:

* **Стилевые тесты.** Чтобы проверить, насколько красота вашего кода соответствует стандартам, вы можете протестировать
ваш код с помощью утилиты _clang-format_. В папке ```materials/linters``` лежит файл ```.clang-format```, который
содержит необходимые настройки для стилевого теста. Данный конфигурационный файл распространяет свое действие на все
файлы, которые лежат с ним в директории или в директориях ниже. Поэтому, чтобы данные настройки применились к вашим
файлам с исходным кодом, скопируйте ```.clang-format``` в папку ```src```. \
\
Чтобы запустить проверку на стиль, выполните следующую команду: \
```clang-format -n src/sourcefile_name.c``` \
\
Чтобы скачать _clang-format_, введите в терминал одну из следующих команд: \
```brew install clang-format``` \
или, если у вас есть root-права (для Ubuntu / Linux Mint / Debian) \
```sudo apt install clang-format```

Google Style: https://google.github.io/styleguide/cppguide.html


* **Тест на корректную работу с памятью.** При написании C-программ очень важно следить за утечками памяти. Для этого в
Unix-подобных операционных системах довольно часто используют утилиту _valgrind_. Однако, на OS X имеются проблемы с
поддержкой _valgrind_, поэтому вместо нее можно использовать утилиту _leaks_. Вдаваться в механизм работы этих утилит
мы сейчас не будем — если интересно, можете почитать в гугле.

Чтобы запустить ваш исполняемый файл с помощью этой утилиты, наберите в терминале: \
```leaks -atExit -- ./main.out | grep LEAK:```

Обратите внимание на команду ```| grep LEAK:```. Мы используем ее для короткого вывода, чтобы видеть только линии с
утечками, если они есть. Если вы хотите увидеть весь вывод, просто удалите эту команду.

При запуске исполняемого файла с помощью _leaks_ может появиться сообщение об ошибке:
> dyld: could not load inserted library ‘/usr/local/lib/libLeaksAtExit.dylib’ because image not found
Ошибка возникает из-за того, что _leaks_ не может найти библиотеку _libLeaksAtExit.dylib_. \
В этом случае вам необходимо ввести следующие команды:
```sh
cd /usr/local/lib
sudo ln -s /Applications/Xcode.app/Contents/Developer/usr/lib/libLeaksAtExit.dylib
```

_Дополнительно:_ \
Используйте флаг ```-exclude``` утилиты _leaks_ для того, чтобы отфильтровать утечки в функциях, где известно об
утечках памяти. Этот флаг позволяет уменьшить количество посторонней информации, сообщаемой _leaks_.

* **Тест сборки.** Программу можно проверить на корректность сборки на тестовой системе. Для этого потребуется
установленный _Docker_. Если на системе есть докер, то можно зайти в директорию `materials/build` и запустить оттуда
скрипт run.sh. Скрипт обернет ваше решение в докер и запустит его вместе с типовым сценарием сборки.
4 changes: 4 additions & 0 deletions materials/linters/.clang-format
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
---
BasedOnStyle: Google
IndentWidth: 4
ColumnLimit: 110
Loading

0 comments on commit e42d06a

Please sign in to comment.