summaryrefslogtreecommitdiff
path: root/std/encoding/_yaml/mark.ts
blob: 35e986cce94ac9de5858a1fc45de427aff2f34ac (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
// Ported from js-yaml v3.13.1:
// https://github.com/nodeca/js-yaml/commit/665aadda42349dcae869f12040d9b10ef18d12da
// Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license.
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.

import { repeat } from "./utils.ts";

export class Mark {
  constructor(
    public name: string,
    public buffer: string,
    public position: number,
    public line: number,
    public column: number,
  ) {}

  public getSnippet(indent = 4, maxLength = 75): string | null {
    if (!this.buffer) return null;

    let head = "";
    let start = this.position;

    while (
      start > 0 &&
      "\x00\r\n\x85\u2028\u2029".indexOf(this.buffer.charAt(start - 1)) === -1
    ) {
      start -= 1;
      if (this.position - start > maxLength / 2 - 1) {
        head = " ... ";
        start += 5;
        break;
      }
    }

    let tail = "";
    let end = this.position;

    while (
      end < this.buffer.length &&
      "\x00\r\n\x85\u2028\u2029".indexOf(this.buffer.charAt(end)) === -1
    ) {
      end += 1;
      if (end - this.position > maxLength / 2 - 1) {
        tail = " ... ";
        end -= 5;
        break;
      }
    }

    const snippet = this.buffer.slice(start, end);
    return `${repeat(" ", indent)}${head}${snippet}${tail}\n${
      repeat(
        " ",
        indent + this.position - start + head.length,
      )
    }^`;
  }

  public toString(compact?: boolean): string {
    let snippet,
      where = "";

    if (this.name) {
      where += `in "${this.name}" `;
    }

    where += `at line ${this.line + 1}, column ${this.column + 1}`;

    if (!compact) {
      snippet = this.getSnippet();

      if (snippet) {
        where += `:\n${snippet}`;
      }
    }

    return where;
  }
}