xaizek / zograscope (License: AGPLv3 only) (since 2018-12-07)
Mainly a syntax-aware diff that also provides a number of additional tools.
<root> / src / Printer.cpp (c66a080d7cd6824f48ffbca98d1dc790ebc3071a) (17KiB) (mode 100644) [raw]
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 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
// Copyright (C) 2017 xaizek <xaizek@posteo.net>
//
// This file is part of zograscope.
//
// zograscope is free software: you can redistribute it and/or modify
// it under the terms of version 3 of the GNU Affero General Public License as
// published by the Free Software Foundation.
//
// zograscope is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with zograscope.  If not, see <http://www.gnu.org/licenses/>.

#include "Printer.hpp"

#include <functional>
#include <iomanip>
#include <ostream>
#include <string>
#include <utility>
#include <vector>

#include <boost/utility/string_ref.hpp>

#include "utils/nums.hpp"
#include "utils/strings.hpp"
#include "utils/time.hpp"
#include "ColorScheme.hpp"
#include "TermHighlighter.hpp"
#include "align.hpp"
#include "decoration.hpp"
#include "tree.hpp"
#include "tree-edit-distance.hpp"

namespace {

class LayoutBuilder;

// Provides parameters of layout.
class Layout
{
    friend class LayoutBuilder;

private:
    // Reference to the builder is saved, so it should outlive layout.
    explicit Layout(const LayoutBuilder &builder,
                    std::vector<int> &&leftWidths);

public:
    // Retrieves width of a marker used in left part of header line.
    int getLeftMarkerWidth() const { return leftNumWidth; }
    // Retrieves width of a marker used in right part of header line.
    int getRightMarkerWidth() const { return rightNumWidth; }

    // Retrieves width of left part of header line excluding middle separator.
    int getLeftHeaderWidth() const { return leftHeaderWidth; }
    // Retrieves width of right part of header line excluding middle separator.
    int getRightHeaderWidth() const { return (usefulWidth - leftHeaderWidth); }

    // Retrieves width of number for the left part including left padding.
    int getLeftNumWidth() const { return 1 + leftNumWidth; }
    // Retrieves width of number for the right part including left padding.
    int getRightNumWidth() const { return 1 + rightNumWidth; }

    // Whether left part should be printed.
    bool isLeftVisible() const { return leftVisible; }
    // Whether right part should be printed.
    bool isRightVisible() const { return rightVisible; }

    // Retrieves maximum width of line on the left part.
    int getMaxLeftWidth() const { return maxLeftWidth; }
    // Retrieves maximum width of line on the right part.
    int getMaxRightWidth() const { return maxRightWidth; }

    // Retrieves width for string on the left.
    int getLeftWidth(boost::string_ref ll, int idx) const
    {
        const int extraWidth = ll.size() - leftWidths[idx];
        if (rightVisible) {
            return maxLeftWidth + extraWidth;
        }
        return wholeWidth              // Total width being used.
             - 1 - 1 - 1               // Marker and left&right padding.
             - (getLeftNumWidth() + 1) // Width of line number column.
             + extraWidth;             // Account for escape sequences.
    }

    // Computes message centering parameters.
    void centerMsg(const std::string &msg, int &leftFill, int &rightFill) const
    {
        const int msgLen = msg.size();
        leftFill = ((leftVisible && rightVisible) ? leftWidth : wholeWidth/2)
                 + 2 - msgLen/2;
        rightFill = wholeWidth - (leftFill + msgLen);
    }

private:
    // Computes whole width of a result.
    int computeWholeWidth() const
    {
        if (leftVisible && rightVisible) {
            return leftPart + 1 + 1 + rightWidth + 1;
        }

        int left = 1 + getLeftMarkerWidth() + 2 + maxLeftHeaderWidth;
        int right = 1 + getRightMarkerWidth() + 2 + maxRightHeaderWidth;

        int headerWidth = left + 3 + right;
        return std::max({ leftPart + 2, rightWidth + 2, headerWidth });
    }

    // Computes width of left header.
    int computeLeftHeaderWidth() const
    {
        if (leftVisible && rightVisible) {
            return leftWidth;
        }

        const int left = 1 + getLeftMarkerWidth() + 2 + maxLeftHeaderWidth;
        const int right = 1 + getRightMarkerWidth() + 2 + maxRightHeaderWidth;

        int width = std::max(left, usefulWidth/2 - 1);
        if (width < right) {
            width = usefulWidth - right;
        }
        return width;
    }

private:
    bool leftVisible, rightVisible;
    int maxLeftWidth, maxRightWidth;
    int leftNumWidth, rightNumWidth;

    int maxLeftHeaderWidth, maxRightHeaderWidth;

    int leftHeaderWidth;
    int leftPart;

    int wholeWidth, usefulWidth;
    int leftWidth, rightWidth;

    std::vector<int> leftWidths;
};

// Collects information needed to compute layout.
class LayoutBuilder
{
    friend class Layout;

public:
    // Starts computing layout by analyzing headers and contents of parts.
    LayoutBuilder(const DiffSource &lsrc, const DiffSource &rsrc,
                  const std::vector<Header> &headers)
    {
        leftVisible = std::find(lsrc.modified.cbegin(), lsrc.modified.cend(),
                                true) != lsrc.modified.cend();
        rightVisible = std::find(rsrc.modified.cbegin(), rsrc.modified.cend(),
                                 true) != rsrc.modified.cend();

        if (!leftVisible && !rightVisible) {
            leftVisible = true;
            rightVisible = true;
        }

        for (const Header &hdr : headers) {
            maxLeftHeaderWidth = std::max<int>(hdr.left.size(),
                                               maxLeftHeaderWidth);
            maxRightHeaderWidth = std::max<int>(hdr.right.size(),
                                                maxRightHeaderWidth);
        }
    }

public:
    // Whether left part should be printed.
    bool isLeftVisible() const { return leftVisible; }
    // Whether right part should be printed.
    bool isRightVisible() const { return rightVisible; }

    // Records maximum line numbers at both sides.
    void setMaxLineNums(int l, int r)
    {
        maxLeftNum = l;
        maxRightNum = r;
    }

    // Records width of a line on the left part.
    void measureLeft(const std::string &line)
    {
        if (!leftVisible) {
            leftWidths.push_back(0);
            return;
        }

        const int width = measureWidth(line);
        leftWidths.push_back(width);
        maxLeftWidth = std::max(width, maxLeftWidth);
    }

    // Records width of a line on the right part.
    void measureRight(const std::string &line)
    {
        if (rightVisible) {
            const int width = measureWidth(line);
            maxRightWidth = std::max(width, maxRightWidth);
        }
    }

    // Produces layout containing all necessary data.
    Layout compute()
    {
        maxLeftWidth = std::max(maxLeftWidth, maxLeftHeaderWidth);
        maxRightWidth = std::max(maxRightWidth, maxRightHeaderWidth);
        return Layout(*this, std::move(leftWidths));
    }

private:
    // Calculates width of a string ignoring embedded escape sequences.
    static unsigned int measureWidth(boost::string_ref s)
    {
        // XXX: we actually print lines without formatting and should be able to
        //      avoid using this function.
        unsigned int valWidth = 0U;
        while (!s.empty()) {
            if (s.front() != '\033') {
                ++valWidth;
                s.remove_prefix(1);
                continue;
            }

            const auto width = s.find('m');
            if (width == std::string::npos) {
                break;
            }
            s.remove_prefix(width + 1U);
        }
        return valWidth;
    }

private:
    bool leftVisible, rightVisible;

    int maxLeftHeaderWidth = 0, maxRightHeaderWidth = 0;
    int maxLeftWidth = 0, maxRightWidth = 0;
    int maxLeftNum = 0, maxRightNum = 0;

    std::vector<int> leftWidths;
};

Layout::Layout(const LayoutBuilder &builder, std::vector<int> &&leftWidths)
    : leftWidths(std::move(leftWidths))
{
    leftVisible = builder.leftVisible;
    rightVisible = builder.rightVisible;

    maxLeftHeaderWidth = builder.maxLeftHeaderWidth;
    maxRightHeaderWidth = builder.maxRightHeaderWidth;

    maxLeftWidth = builder.maxLeftWidth;
    maxRightWidth = builder.maxRightWidth;

    leftNumWidth = countWidth(builder.maxLeftNum);
    rightNumWidth = countWidth(builder.maxRightNum);

    leftPart = leftVisible ? (leftNumWidth + 1) + 1 + 1 + maxLeftWidth : 0;
    rightWidth = rightVisible ? (rightNumWidth + 1) + 1 + 1 + maxRightWidth : 0;
    wholeWidth = computeWholeWidth();
    usefulWidth = wholeWidth - 3;
    leftWidth = rightVisible ? leftPart : wholeWidth - 2;

    leftHeaderWidth = computeLeftHeaderWidth();
}

// This class is responsible for formatting output while printing it to a
// stream.
class Outliner
{
public:
    // Reference to layout is saved, so it should outlive outliner.
    Outliner(std::ostream &os, const Layout &layout) : os(os), layout(layout)
    {
        leftMarker = ' '
                   + std::string(layout.getLeftMarkerWidth(), '-')
                   + "  ";
        rightMarker = ' '
                    + std::string(layout.getRightMarkerWidth(), '+')
                    + "  ";
    }

public:
    // Prints horizontal separator.
    void printSeparator()
    {
        using namespace decor::literals;

        os << std::setfill('~')
           << std::setw(layout.getLeftHeaderWidth() + 1) << (231_fg << "")
           << (decor::bold << '!')
           << std::setw(layout.getRightHeaderWidth() + 1) << (231_fg << "")
           << std::setfill(' ')
           << '\n';
    }

    // Prints single header.
    void printHeader(const Header &hdr)
    {
        using namespace decor::literals;

        auto title = 231_fg + decor::bold;
        os << (title << std::left
                     << std::setw(layout.getLeftHeaderWidth())
                     << leftMarker + hdr.left
                     << " ! "
                     << std::setw(layout.getRightHeaderWidth())
                     << rightMarker + hdr.right)
           << '\n';
    }

    // Prints a horizontally centered message.
    void printMsg(const std::string &msg)
    {
        using namespace decor::literals;

        int leftFill, rightFill;
        layout.centerMsg(msg, leftFill, rightFill);

        os << std::right << std::setfill('.')
           << (251_fg << std::setw(leftFill) << "")
           << msg
           << (251_fg << std::setw(rightFill) << "")
           << '\n' << std::setfill(' ');
    }

    // Prints line of the left part.
    void printLeftLine(int lineNum, boost::string_ref str)
    {
        const int width = layout.getLeftWidth(str, leftWidthIndex++);
        printLine(lineNum, str, layout.getLeftNumWidth(), width);
    }

    // Prints line of the right part.
    void printRightLine(int lineNum, boost::string_ref str)
    {
        printLine(lineNum, str, layout.getRightNumWidth(), 0);
    }

    // Prints blank line of the left part.
    void printLeftBlank(int lineNum)
    {
        printBlank(lineNum, layout.getLeftNumWidth(), layout.getMaxLeftWidth());
    }

    // Prints blank line of the right part.
    void printRightBlank(int lineNum)
    {
        printBlank(lineNum, layout.getRightNumWidth(),
                   layout.getMaxRightWidth());
    }

    // Prints marker between two parts.
    void printMarker(char marker, ColorGroup color)
    {
        if (layout.isLeftVisible()) {
            os << ' ';
        }
        os << (cs[color] << marker);
        if (layout.isRightVisible()) {
            os << ' ';
        }
    }

    // Advances to next line of parts.
    void nextLine()
    {
        os << '\n';
    }

private:
    // Formats and prints single line with its line number.
    void printLine(int lineNum, boost::string_ref str,
                   int numColWidth, int width)
    {
        os << (lineNo << std::right << std::setw(numColWidth) << lineNum << ' ')
           << ' ' << std::left << std::setw(width) << str;
    }

    // Formats and prints single blank line with its line number.
    void printBlank(int lineNum, int numColWidth, int width)
    {
        using namespace decor::literals;

        os << (lineNo << std::right << std::setw(numColWidth + 1)
                      << (noLineMarker(lineNum) + ' '))
           << ' ' << std::left << std::setw(width)
           << (235_bg << "");
    }

    // Generates string that should be used instead of line number.  Takes line
    // number of the last displayed line (0 if none was printed) as argument.
    static std::string noLineMarker(int at)
    {
        return std::string(countWidth(at), '-');
    }

private:
    std::ostream &os;        // Output stream.
    const Layout &layout;    // Computed layout.
    std::string leftMarker;  // Left marker for headers.
    std::string rightMarker; // Right marker for headers.

    // Color scheme.
    ColorScheme cs;
    // Line number style.
    decor::Decoration lineNo = cs[ColorGroup::LineNo];
    // Next line index of the left part (needed to correct maximum width).
    int leftWidthIndex = 0;
};

}

Printer::Printer(const Node &left, const Node &right, const Language &lang,
                 std::ostream &os)
    : left(left), right(right), lang(lang), os(os)
{
}

Printer::Printer(const Node &left, std::vector<std::string> &&leftAnnots,
                 const Node &right, std::vector<std::string> &&rightAnnots,
                 const Language &lang, std::ostream &os)
    : left(left), right(right),
      leftAnnots(std::move(leftAnnots)), rightAnnots(std::move(rightAnnots)),
      lang(lang), os(os)
{
}

void
Printer::addHeader(Header header)
{
    headers.emplace_back(std::move(header));
}

void
Printer::print(TimeReport &tr)
{
    auto diffingTimer = tr.measure("printing");

    // Do comparison without highlighting as it skews alignment results.
    DiffSource lsrc = (tr.measure("left-align-print"), DiffSource(left));
    DiffSource rsrc = (tr.measure("right-align-print"), DiffSource(right));
    std::vector<DiffLine> diff = (tr.measure("align"),
                                  makeDiff(std::move(lsrc), std::move(rsrc)));

    auto timer = tr.measure("printing");

    TermHighlighter lh(left, lang, true);
    TermHighlighter rh(right, lang, false);
    std::vector<std::string> l(lsrc.lines.size());
    std::vector<std::string> r(rsrc.lines.size());

    LayoutBuilder layoutBuilder(lsrc, rsrc, headers);

    auto annotate = [](std::string &str,
                       const std::vector<std::string> &annots,
                       std::size_t index) {
        if (index < annots.size()) {
            str.insert(str.begin(),
                       annots[index].cbegin(), annots[index].cend());
        }
    };

    unsigned int i = 0U, j = 0U;
    for (DiffLine d : diff) {
        if (d.type == Diff::Fold) {
            i += d.data;
            j += d.data;
            continue;
        }

        if (d.type != Diff::Right) {
            if (layoutBuilder.isLeftVisible()) {
                l[i] = lh.print(i + 1, 1);
                annotate(l[i], leftAnnots, i);
            }
            layoutBuilder.measureLeft(l[i++]);
        }
        if (d.type != Diff::Left) {
            if (layoutBuilder.isRightVisible()) {
                r[j] = rh.print(j + 1, 1);
                annotate(r[j], rightAnnots, j);
            }
            layoutBuilder.measureRight(r[j++]);
        }

        // Record last non-folded indices.
        layoutBuilder.setMaxLineNums(i, j);
    }

    Layout layout = layoutBuilder.compute();
    Outliner outliner(os, layout);

    outliner.printSeparator();
    for (const Header &hdr : headers) {
        outliner.printHeader(hdr);
    }
    outliner.printSeparator();

    i = 0U;
    j = 0U;
    for (DiffLine d : diff) {
        boost::string_ref ll, rl;
        char marker = '?';
        ColorGroup markerColor = ColorGroup::None;

        switch (d.type) {
            case Diff::Left:      ll = l[i++];              marker = '-';
                                  markerColor = ColorGroup::Deleted;
                                  break;
            case Diff::Right:                  rl = r[j++]; marker = '+';
                                  markerColor = ColorGroup::Inserted;
                                  break;
            case Diff::Identical: ll = l[i++]; rl = r[j++]; marker = '|'; break;
            case Diff::Different: ll = l[i++]; rl = r[j++]; marker = '~';
                                  markerColor = ColorGroup::Updated;
                                  break;

            case Diff::Fold:
                i += d.data;
                j += d.data;
                outliner.printMsg(" @@ folded " + std::to_string(d.data) +
                                  " identical lines @@ ");
                continue;
        }

        if ((!layout.isLeftVisible() && d.type == Diff::Left) ||
            (!layout.isRightVisible() && d.type == Diff::Right))
        {
            // Skip blank lines if only one version is displayed.
            continue;
        }

        if (layout.isLeftVisible()) {
            if (d.type == Diff::Right) {
                outliner.printLeftBlank(i);
            } else {
                outliner.printLeftLine(i, ll);
            }
        }

        outliner.printMarker(marker, markerColor);

        if (layout.isRightVisible()) {
            if (d.type == Diff::Left) {
                outliner.printRightBlank(j);
            } else {
                outliner.printRightLine(j, rl);
            }
        }

        outliner.nextLine();
    }
}
Hints

Before first commit, do not forget to setup your git environment:
git config --global user.name "your_name_here"
git config --global user.email "your@email_here"

Clone this repository using HTTP(S):
git clone https://code.reversed.top/user/xaizek/zograscope

Clone this repository using ssh (do not forget to upload a key first):
git clone ssh://rocketgit@code.reversed.top/user/xaizek/zograscope

You are allowed to anonymously push to this repository.
This means that your pushed commits will automatically be transformed into a pull request:
... clone the repository ...
... make some changes and some commits ...
git push origin master