CMake многострочное сообщение с FATAL_ERROR - PullRequest
0 голосов
/ 21 мая 2018

CMake документация (например, текущая версия 3.11.2 ) заявляет

CMake Предупреждение и сообщение об ошибке текст отображается с использованием простого языка разметки.Текст без отступов форматируется в виде строк с абзацами, разделенными символами новой строки.Текст с отступом считается предварительно отформатированным.

Однако в нем не упоминается никакой формат разметки.Если только «без отступа» и «с отступом» - это все, что есть в «простой разметке».

В любом случае мне не удалось заставить его работать в режиме FATAL_ERROR.

Более тогоЯ заметил, что в режиме STATUS сообщение печатается с начальным значением -- (две черточки и пробел).Хотя с FATAL_ERROR каждый разрыв строки в сообщении превращается в две строки, что (ИМХО) выглядит ужасно.

Теперь у меня есть многострочное сообщение, в котором перечисляется, что не так в CMAKE_BUILD_TYPE и какие значения принимаются,Из-за вышеупомянутых проблем я закончил тем, что напечатал сообщение как STATUS и сделал отступ в следующих строках с тремя пробелами (чтобы они хорошо совпали с --).Затем я делаю простой FATAL_ERROR, повторяя только «строку заголовка» (заявляя, что CMAKE_BUILD_TYPE неверно).Это выглядит приемлемо как для вывода на консоль, так и на cmake-gui.(Хотя отступ в 3 пробела не нужен cmake-gui ...)

Однако я удивлен, насколько плохо описана эта тема.И, похоже, так было давно - см., Например, вопрос [CMake] Дополнительные пустые строки с SEND_ERROR и FATAL_ERROR?! , оставшиеся без ответа в течение почти 9 лет ...

Есть ли какие-либопередовая практика, советы или советы по обработке таких сообщений?Или их следует избегать в первую очередь?

1 Ответ

0 голосов
/ 26 июня 2018

Ты прав.«Простая разметка» является либо без отступа (не отформатированный), либо с отступом (отформатированный).Кроме того, текст без отступов находится в параграфах , разделенных символами новой строки.Вот почему вы заканчиваете пустыми строками между абзацами.

Вот краткое объяснение различных видов сообщений.Типы предупреждений и типы ошибок ведут себя так же, как форматированный и неформатированный текст.Разница, конечно, в том, что происходит с фазами обработки и генерации CMake.Для удобства чтения вы можете разбить строки на несколько частей в двойных кавычках, которые будут объединены.

# STATUS
message(STATUS
    "This is a status message. It is prefixed with \"-- \". It goes to stdout. The "
    "lines will wrap according to the width of your terminal.\n"
    "New lines will begin a new line at column 1, but without the \"-- \" prefix, "
    "unless you provide it; they will not create a blank line (i.e., new "
    "paragraph).   Spacing between sentences is unaltered by CMake.\n"
    "-- Here's a new paragraph with an explicit \"-- \" prefix added.")

# no mode given (informational)
message(
    "This is an informational message. It goes to stderr. Each line begins at column "
    "1. The lines will wrap according to the width of your terminal.\n"
    "New lines will begin a new line at column 1; they will not create a blank line "
    "(i.e., new paragraph).   Spacing between sentences is unaltered by CMake (3 spaces "
    "preceded this sentence.).")

# WARNING--unformatted
message(WARNING
    "This is an unformatted warning message.   It goes to stderr. Each line begins "
    "at column 3. The lines will wrap at a particular column (it appears to be "
    "column 77, set within CMake) and wrap back to column 3.\n"
    "New lines will begin a new paragraph, so they will create a blank line. A final "
    "thing about unformatted messages: They will separate sentences with 2 spaces, "
    "even if your string had something  different.")

# WARNING--formatted and unformatted
message(WARNING
    " This is a formatted warning message. It goes to stderr. Formatted lines will"
    " be indented an additional 2 spaces beyond what was provided in the output"
    " string. The lines will wrap according to the width of your terminal.\n"
    " Indented new lines will begin a new line. They will not create a blank line."
    " If you separate sentences with 1 space, that's what you'll get.  If you"
    " separate them with 2 spaces, that's also what you'll get.\n"
    " If you want to control the width of the formatted paragraphs\n"
    " (a good practice), just keep track of the width of each line and place\n"
    " a \"\\n\" at the end of each line.\n \n"
    " And, if you want a blank line between paragraphs, just place \"\\n \\n\"\n"
    " (i.e., 2 newlines separated by a space) at the end of the first paragraph.\n"
    "Non-indented new lines, however, will be treated like unformatted warning "
    "messages, described above. They will begin at and wrap to column 3. They begin "
    "a new paragraph, so they will create a blank line.    There will be 2 spaces "
    "between sentences, regardless of how many you placed after the period (In the "
    "script, there were 4 spaces before this sentence).\n"
    "And, as you'd expect, a second unindented paragraph will be preceded by a "
    "blank line. But why would you mix formatted and unformatted text?")

Я сохранил это в Message.cmake и вызвал его с помощью cmake -P Message.cmake 2> output.txt.В результате получается следующий стандартный вывод:

-- This is a status message. It is prefixed with "-- ". It goes to stdout. The lines will wrap according to the width of your terminal.
New lines will begin a new line at column 1, but without the "-- " prefix, unless you provide it; they will not create a blank line (i.e., new paragraph).   Spacing between sentences is unaltered by CMake.
-- Here's a new paragraph with an explicit "-- " prefix added.

Файл output.txt содержит:

This is an informational message. It goes to stderr. Each line begins at column 1. The lines will wrap according to the width of your terminal.
New lines will begin a new line at column 1; they will not create a blank line (i.e., new paragraph).   Spacing between sentences is unaltered by CMake (3 spaces preceded this sentence.).
CMake Warning at MessageScript.cmake:19 (message):
  This is an unformatted warning message.  It goes to stderr.  Each line
  begins at column 3.  The lines will wrap at a particular column (it appears
  to be column 77, set within CMake) and wrap back to column 3.

  New lines will begin a new paragraph, so they will create a blank line.  A
  final thing about unformatted messages: They will separate sentences with 2
  spaces, even if your string had something different.


CMake Warning at MessageScript.cmake:28 (message):
   This is a formatted warning message. It goes to stderr. Formatted lines will be indented an additional 2 spaces beyond what was provided in the output string. The lines will wrap according to the width of your terminal.
   Indented new lines will begin a new line. They will not create a blank line. If you separate sentences with 1 space, that's what you'll get.  If you separate them with 2 spaces, that's also what you'll get.
   If you want to control the width of the formatted paragraphs
   (a good practice), just keep track of the width of each line and place
   a "\n" at the end of each line.

   And, if you want a blank line between paragraphs, just place "\n \n"
   (i.e., 2 newlines separated by a space) at the end of the first paragraph.

  Non-indented new lines, however, will be treated like unformatted warning
  messages, described above.  They will begin at and wrap to column 3.  They
  begin a new paragraph, so they will create a blank line.  There will be 2
  spaces between sentences, regardless of how many you placed after the
  period (In the script, there were 4 spaces before this sentence).

  And, as you'd expect, a second unindented paragraph will be preceded by a
  blank line.  But why would you mix formatted and unformatted text?

РЕЗЮМЕ

ИНФОРМАЦИОННЫЕ СООБЩЕНИЯ (режим не указан)

  • начинаться со столбца 1
  • перенос в окне терминала до новой строки
  • переход к stderr
  • новые абзацы начинаются без предшествующей пустой строки
  • предложение и интервал между словами сохраняются

СООБЩЕНИЯ СОСТОЯНИЯ

  • начинаются со столбца 1, сПрефикс "-" в первом абзаце
  • переносится в окне терминала до новой строки
  • иди в стандартный вывод
  • новые абзацы начинаются без предшествующей пустой строки
  • предложение иинтервал между словами сохранен

НЕФОРМИРОВАННЫЕ СООБЩЕНИЯ О ПРЕДУПРЕЖДЕНИИ И ОШИБКАХ (строки без отступов)

  • начало в столбце 3
  • перенос в столбец 77
  • перейти к stderr
  • новым абзацам предшествует пустая строка
  • предложения, разделенные двумя пробелами;слова на 1 пробел

ФОРМАТИРОВАННЫЕ ПРЕДУПРЕЖДЕНИЯ И СООБЩЕНИЯ ОБ ОШИБКАХ (строки с отступами)

  • начинаются со столбца 3 плюс любой отступ, который имела строка
  • перенос в окне терминала до новой строки
  • переход к stderr
  • новые абзацы начинаются без предшествующей пустой строки
  • предложение и интервал слов сохраняются
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...