summaryrefslogtreecommitdiff
path: root/tools/node_modules/eslint/node_modules/eslint-plugin-jsdoc/dist/rules/sortTags.js
blob: 4c81206200170616b487be9d33f77b40511803eb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _defaultTagOrder = _interopRequireDefault(require("../defaultTagOrder"));
var _iterateJsdoc = _interopRequireDefault(require("../iterateJsdoc"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// eslint-disable-next-line complexity -- Temporary
var _default = (0, _iterateJsdoc.default)(({
  context,
  jsdoc,
  utils
}) => {
  const {
    linesBetween = 1,
    tagSequence = _defaultTagOrder.default,
    alphabetizeExtras = false,
    reportTagGroupSpacing = true,
    reportIntraTagGroupSpacing = true
  } = context.options[0] || {};
  const tagList = tagSequence.flatMap(obj => {
    /* typeof obj === 'string' ? obj : */
    return obj.tags;
  });
  const otherPos = tagList.indexOf('-other');
  const endPos = otherPos > -1 ? otherPos : tagList.length;
  let ongoingCount = 0;
  for (const [idx, tag] of jsdoc.tags.entries()) {
    tag.originalIndex = idx;
    ongoingCount += tag.source.length;
    tag.originalLine = ongoingCount;
  }
  let firstChangedTagLine;
  let firstChangedTagIndex;
  const sortedTags = JSON.parse(JSON.stringify(jsdoc.tags));
  sortedTags.sort(({
    tag: tagNew
  }, {
    originalIndex,
    originalLine,
    tag: tagOld
  }) => {
    // Optimize: Just keep relative positions if the same tag name
    if (tagNew === tagOld) {
      return 0;
    }
    const checkOrSetFirstChanged = () => {
      if (!firstChangedTagLine || originalLine < firstChangedTagLine) {
        firstChangedTagLine = originalLine;
        firstChangedTagIndex = originalIndex;
      }
    };
    const newPos = tagList.indexOf(tagNew);
    const oldPos = tagList.indexOf(tagOld);
    const preferredNewPos = newPos === -1 ? endPos : newPos;
    const preferredOldPos = oldPos === -1 ? endPos : oldPos;
    if (preferredNewPos < preferredOldPos) {
      checkOrSetFirstChanged();
      return -1;
    }
    if (preferredNewPos > preferredOldPos) {
      return 1;
    }

    // preferredNewPos === preferredOldPos
    if (!alphabetizeExtras ||
    // Optimize: If tagNew (or tagOld which is the same) was found in the
    //   priority array, it can maintain its relative position—without need
    //   of alphabetizing (secondary sorting)
    newPos >= 0) {
      return 0;
    }
    if (tagNew < tagOld) {
      checkOrSetFirstChanged();
      return -1;
    }

    // tagNew > tagOld
    return 1;
  });
  if (firstChangedTagLine === undefined) {
    // Should be ordered by now

    const lastTagsOfGroup = [];
    const badLastTagsOfGroup = [];
    const countTagEmptyLines = tag => {
      return tag.source.reduce((acc, {
        tokens: {
          description,
          name,
          type,
          end,
          tag: tg
        }
      }) => {
        const empty = !tg && !type && !name && !description;
        // Reset the count so long as there is content
        return empty ? acc + (empty && !end) : 0;
      }, 0);
    };
    let idx = 0;
    for (const {
      tags
    } of tagSequence) {
      let innerIdx;
      let currentTag;
      let lastTag;
      do {
        currentTag = jsdoc.tags[idx];
        if (!currentTag) {
          idx++;
          break;
        }
        innerIdx = tags.indexOf(currentTag.tag);
        if (innerIdx === -1 && (
        // eslint-disable-next-line no-loop-func -- Safe
        !tags.includes('-other') || tagSequence.some(({
          tags: tgs
        }) => {
          return tgs.includes(currentTag.tag);
        }))) {
          idx++;
          break;
        }
        lastTag = currentTag;
        idx++;
      } while (true);
      idx--;
      if (lastTag) {
        lastTagsOfGroup.push(lastTag);
        const ct = countTagEmptyLines(lastTag);
        if (ct !== linesBetween &&
        // Use another rule for adding to end (should be of interest outside this rule)
        jsdoc.tags[idx]) {
          badLastTagsOfGroup.push([lastTag, ct]);
        }
      }
    }
    if (reportTagGroupSpacing && badLastTagsOfGroup.length) {
      const fixer = tg => {
        return () => {
          // Due to https://github.com/syavorsky/comment-parser/issues/110 ,
          //  we have to modify `jsdoc.source` rather than just modify tags
          //  directly
          for (const [currIdx, {
            tokens
          }] of jsdoc.source.entries()) {
            if (tokens.tag !== '@' + tg.tag) {
              continue;
            }

            // Cannot be `tokens.end`, as dropped off last tag, so safe to
            //  go on
            let newIdx = currIdx;
            const emptyLine = () => {
              return {
                tokens: utils.seedTokens({
                  delimiter: '*',
                  start: jsdoc.source[newIdx - 1].tokens.start
                })
              };
            };
            let existingEmptyLines = 0;
            while (true) {
              var _jsdoc$source$newIdx;
              const nextTokens = (_jsdoc$source$newIdx = jsdoc.source[++newIdx]) === null || _jsdoc$source$newIdx === void 0 ? void 0 : _jsdoc$source$newIdx.tokens;

              /* istanbul ignore if -- Guard */
              if (!nextTokens) {
                return;
              }

              // Should be no `nextTokens.end` to worry about since ignored
              //  if not followed by tag

              if (nextTokens.tag) {
                // Haven't made it to last tag instance yet, so keep looking
                if (nextTokens.tag === tokens.tag) {
                  existingEmptyLines = 0;
                  continue;
                }
                const lineDiff = linesBetween - existingEmptyLines;
                if (lineDiff > 0) {
                  const lines = Array.from({
                    length: lineDiff
                  }, () => {
                    return emptyLine();
                  });
                  jsdoc.source.splice(newIdx, 0, ...lines);
                } else {
                  // lineDiff < 0
                  jsdoc.source.splice(newIdx + lineDiff, -lineDiff);
                }
                break;
              }
              const empty = !nextTokens.type && !nextTokens.name && !nextTokens.description;
              if (empty) {
                existingEmptyLines++;
              } else {
                // Has content again, so reset empty line count
                existingEmptyLines = 0;
              }
            }
            break;
          }
          for (const [srcIdx, src] of jsdoc.source.entries()) {
            src.number = srcIdx;
          }
        };
      };
      for (const [tg, ct] of badLastTagsOfGroup) {
        utils.reportJSDoc('Tag groups do not have the expected whitespace', tg, fixer(tg, ct));
      }
      return;
    }
    if (!reportIntraTagGroupSpacing) {
      return;
    }
    for (const [tagIdx, tag] of jsdoc.tags.entries()) {
      if (!jsdoc.tags[tagIdx + 1] || lastTagsOfGroup.includes(tag)) {
        continue;
      }
      const ct = countTagEmptyLines(tag);
      if (ct) {
        // eslint-disable-next-line complexity -- Temporary
        const fixer = () => {
          let foundFirstTag = false;
          let currentTag;
          for (const [currIdx, {
            tokens: {
              description,
              name,
              type,
              end,
              tag: tg
            }
          }] of jsdoc.source.entries()) {
            if (tg) {
              foundFirstTag = true;
              currentTag = tg;
            }
            if (!foundFirstTag) {
              continue;
            }
            if (currentTag && !tg && !type && !name && !description && !end) {
              let nextIdx = currIdx;
              let ignore = true;
              // Even if a tag of the same name as the last tags in a group,
              //  could still be an earlier tag in that group

              // eslint-disable-next-line no-loop-func -- Safe
              if (lastTagsOfGroup.some(lastTagOfGroup => {
                return currentTag === '@' + lastTagOfGroup.tag;
              })) {
                while (true) {
                  var _jsdoc$source$nextIdx;
                  const nextTokens = (_jsdoc$source$nextIdx = jsdoc.source[++nextIdx]) === null || _jsdoc$source$nextIdx === void 0 ? void 0 : _jsdoc$source$nextIdx.tokens;
                  if (!nextTokens) {
                    break;
                  }
                  if (!nextTokens.tag) {
                    continue;
                  }

                  // Followed by the same tag name, so not actually last in group,
                  //   and of interest
                  if (nextTokens.tag === currentTag) {
                    ignore = false;
                  }
                }
              } else {
                while (true) {
                  var _jsdoc$source$nextIdx2;
                  const nextTokens = (_jsdoc$source$nextIdx2 = jsdoc.source[++nextIdx]) === null || _jsdoc$source$nextIdx2 === void 0 ? void 0 : _jsdoc$source$nextIdx2.tokens;
                  if (!nextTokens || nextTokens.end) {
                    break;
                  }

                  // Not the very last tag, so don't ignore
                  if (nextTokens.tag) {
                    ignore = false;
                    break;
                  }
                }
              }
              if (!ignore) {
                jsdoc.source.splice(currIdx, 1);
                for (const [srcIdx, src] of jsdoc.source.entries()) {
                  src.number = srcIdx;
                }
              }
            }
          }
        };
        utils.reportJSDoc('Intra-group tags have unexpected whitespace', tag, fixer);
      }
    }
    return;
  }
  const firstLine = utils.getFirstLine();
  const fix = () => {
    const itemsToMoveRange = [...Array.from({
      length: jsdoc.tags.length - firstChangedTagIndex
    }).keys()];
    const unchangedPriorTagDescriptions = jsdoc.tags.slice(0, firstChangedTagIndex).reduce((ct, {
      source
    }) => {
      return ct + source.length - 1;
    }, 0);

    // This offset includes not only the offset from where the first tag
    //   must begin, and the additional offset of where the first changed
    //   tag begins, but it must also account for prior descriptions
    const initialOffset = firstLine + firstChangedTagIndex +
    // May be the first tag, so don't try finding a prior one if so
    unchangedPriorTagDescriptions;

    // Use `firstChangedTagLine` for line number to begin reporting/splicing
    for (const idx of itemsToMoveRange) {
      utils.removeTag(idx + firstChangedTagIndex);
    }
    const changedTags = sortedTags.slice(firstChangedTagIndex);
    let extraTagCount = 0;
    for (const idx of itemsToMoveRange) {
      const changedTag = changedTags[idx];
      utils.addTag(changedTag.tag, extraTagCount + initialOffset + idx, {
        ...changedTag.source[0].tokens,
        // `comment-parser` puts the `end` within the `tags` section, so
        //   avoid adding another to jsdoc.source
        end: ''
      });
      for (const {
        tokens
      } of changedTag.source.slice(1)) {
        if (!tokens.end) {
          utils.addLine(extraTagCount + initialOffset + idx + 1, {
            ...tokens,
            end: ''
          });
          extraTagCount++;
        }
      }
    }
  };
  utils.reportJSDoc(`Tags are not in the prescribed order: ${tagList.join(', ') || '(alphabetical)'}`, jsdoc.tags[firstChangedTagIndex], fix, true);
}, {
  iterateAllJsdocs: true,
  meta: {
    docs: {
      description: 'Sorts tags by a specified sequence according to tag name.',
      url: 'https://github.com/gajus/eslint-plugin-jsdoc#eslint-plugin-jsdoc-rules-sort-tags'
    },
    fixable: 'code',
    schema: [{
      additionalProperties: false,
      properties: {
        alphabetizeExtras: {
          type: 'boolean'
        },
        linesBetween: {
          type: 'integer'
        },
        reportIntraTagGroupSpacing: {
          type: 'boolean'
        },
        reportTagGroupSpacing: {
          type: 'boolean'
        },
        tagSequence: {
          items: {
            properties: {
              tags: {
                items: {
                  type: 'string'
                },
                type: 'array'
              }
            },
            type: 'object'
          },
          type: 'array'
        }
      },
      type: 'object'
    }],
    type: 'suggestion'
  }
});
exports.default = _default;
module.exports = exports.default;
//# sourceMappingURL=sortTags.js.map