Welcome to mirror list, hosted at ThFree Co, Russian Federation.

checkLinks.js « doc « tools - github.com/nodejs/node.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 97210ca03076e4d961a9c1fc0d11dac395f3f1dc (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
'use strict';

const fs = require('fs');
const { extname, join, resolve } = require('path');
const unified = require('unified');
const { pathToFileURL } = require('url');
const DIR = resolve(process.argv[2]);

console.log('Running Markdown link checker...');
findMarkdownFilesRecursively(DIR);

function* getLinksRecursively(node) {
  if (node.url && !node.url.startsWith('#')) {
    yield node;
  }
  for (const child of node.children || []) {
    yield* getLinksRecursively(child);
  }
}

function findMarkdownFilesRecursively(dirPath) {
  const entries = fs.readdirSync(dirPath, { withFileTypes: true });

  for (const entry of entries) {
    const path = join(dirPath, entry.name);

    if (
      entry.isDirectory() &&
      entry.name !== 'api' &&
      entry.name !== 'changelogs' &&
      entry.name !== 'deps' &&
      entry.name !== 'fixtures' &&
      entry.name !== 'node_modules' &&
      entry.name !== 'out' &&
      entry.name !== 'tmp'
    ) {
      findMarkdownFilesRecursively(path);
    } else if (entry.isFile() && extname(entry.name) === '.md') {
      checkFile(path);
    }
  }
}

function checkFile(path) {
  const tree = unified()
    .use(require('remark-parse'))
    .parse(fs.readFileSync(path));

  const base = pathToFileURL(path);
  let previousDefinitionLabel;
  for (const node of getLinksRecursively(tree)) {
    const targetURL = new URL(node.url, base);
    if (targetURL.protocol === 'file:' && !fs.existsSync(targetURL)) {
      const { line, column } = node.position.start;
      console.error((process.env.GITHUB_ACTIONS ?
        `::error file=${path},line=${line},col=${column}::` : '') +
        `Broken link at ${path}:${line}:${column} (${node.url})`);
      process.exitCode = 1;
    }
    if (node.type === 'definition') {
      if (previousDefinitionLabel &&
          previousDefinitionLabel > node.label) {
        const { line, column } = node.position.start;
        console.error((process.env.GITHUB_ACTIONS ?
          `::error file=${path},line=${line},col=${column}::` : '') +
          `Unordered reference at ${path}:${line}:${column} (` +
          `"${node.label}" should be before "${previousDefinitionLabel})"`
        );
        process.exitCode = 1;
      }
      previousDefinitionLabel = node.label;
    }
  }
}