1# -*- coding: utf-8 -*-
2# Copyright (C) 2016 Adrien Vergé
3#
4# This program is free software: you can redistribute it and/or modify
5# it under the terms of the GNU General Public License as published by
6# the Free Software Foundation, either version 3 of the License, or
7# (at your option) any later version.
8#
9# This program is distributed in the hope that it will be useful,
10# but WITHOUT ANY WARRANTY; without even the implied warranty of
11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12# GNU General Public License for more details.
13#
14# You should have received a copy of the GNU General Public License
15# along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
17"""
18Use this rule to require or forbid the use of document start marker (``---``).
19
20.. rubric:: Options
21
22* Set ``present`` to ``true`` when the document start marker is required, or to
23  ``false`` when it is forbidden.
24
25.. rubric:: Default values (when enabled)
26
27.. code-block:: yaml
28
29 rules:
30   document-start:
31     present: true
32
33.. rubric:: Examples
34
35#. With ``document-start: {present: true}``
36
37   the following code snippet would **PASS**:
38   ::
39
40    ---
41    this:
42      is: [a, document]
43    ---
44    - this
45    - is: another one
46
47   the following code snippet would **FAIL**:
48   ::
49
50    this:
51      is: [a, document]
52    ---
53    - this
54    - is: another one
55
56#. With ``document-start: {present: false}``
57
58   the following code snippet would **PASS**:
59   ::
60
61    this:
62      is: [a, document]
63    ...
64
65   the following code snippet would **FAIL**:
66   ::
67
68    ---
69    this:
70      is: [a, document]
71    ...
72"""
73
74
75import yaml
76
77from yamllint.linter import LintProblem
78
79
80ID = 'document-start'
81TYPE = 'token'
82CONF = {'present': bool}
83DEFAULT = {'present': True}
84
85
86def check(conf, token, prev, next, nextnext, context):
87    if conf['present']:
88        if (isinstance(prev, (yaml.StreamStartToken,
89                              yaml.DocumentEndToken,
90                              yaml.DirectiveToken)) and
91            not isinstance(token, (yaml.DocumentStartToken,
92                                   yaml.DirectiveToken,
93                                   yaml.StreamEndToken))):
94            yield LintProblem(token.start_mark.line + 1, 1,
95                              'missing document start "---"')
96
97    else:
98        if isinstance(token, yaml.DocumentStartToken):
99            yield LintProblem(token.start_mark.line + 1,
100                              token.start_mark.column + 1,
101                              'found forbidden document start "---"')
102