navid/veins / master / xveins/src/worktree/attr.cpp

attr.cpp

← xveins/src/worktree · 12929 bytes · raw · download

#include "cli/local_commands.h"

#include "core/common.h"
#include "store/store.h"
#include "worktree/pathspec.h"

#include <iostream>
#include <string_view>
#include <vector>

namespace vn {

namespace {

bool attr_is_flag(std::string_view arg) {
    return !arg.empty() && arg.front() == '-';
}

bool attr_is_space(char c) {
    return c == ' ' || c == '\t';
}

std::string_view attr_trim(std::string_view text) {
    while (!text.empty() &&
           (attr_is_space(text.front()) || text.front() == '\r' || text.front() == '\n'))
        text.remove_prefix(1);
    while (!text.empty() &&
           (attr_is_space(text.back()) || text.back() == '\r' || text.back() == '\n'))
        text.remove_suffix(1);
    return text;
}

bool load_attribs(const fs::path& path, std::string& data) {
    if (auto existing = read_file_opt(path)) {
        data.assign(reinterpret_cast<const char*>(existing->data()), existing->size());
        return true;
    }
    if (path_exists(path)) {
        error_prefix();
        std::cout << "cannot read .vnattribs\n";
        return false;
    }
    return true;
}

std::vector<std::string> tokenize(std::string_view line) {
    std::vector<std::string> tokens;
    std::size_t position = 0;
    while (position < line.size()) {
        while (position < line.size() && attr_is_space(line[position]))
            ++position;
        const std::size_t start = position;
        while (position < line.size() && !attr_is_space(line[position]))
            ++position;
        if (position > start)
            tokens.emplace_back(line.substr(start, position - start));
    }
    return tokens;
}

enum class Attr { Gen, Txt, Bin, Lf, Crlf, Cr };

std::optional<Attr> parse_attr(std::string_view name) {
    if (name == "gen")
        return Attr::Gen;
    if (name == "txt")
        return Attr::Txt;
    if (name == "bin")
        return Attr::Bin;
    if (name == "lf")
        return Attr::Lf;
    if (name == "crlf")
        return Attr::Crlf;
    if (name == "cr")
        return Attr::Cr;
    return std::nullopt;
}

std::string_view canonical_token(Attr attr) {
    switch (attr) {
    case Attr::Gen:
        return "gen";
    case Attr::Txt:
        return "txt";
    case Attr::Bin:
        return "bin";
    case Attr::Lf:
        return "eol:lf";
    case Attr::Crlf:
        return "eol:crlf";
    case Attr::Cr:
        return "eol:cr";
    }
    return {};
}

bool is_attr_token(std::string_view token, Attr attr) {
    switch (attr) {
    case Attr::Gen:
        return token == "gen" || token == "-gen";
    case Attr::Txt:
        return token == "txt" || token == "-txt";
    case Attr::Bin:
        return token == "bin" || token == "-bin";
    case Attr::Lf:
        return token == "eol:lf";
    case Attr::Crlf:
        return token == "eol:crlf";
    case Attr::Cr:
        return token == "eol:cr";
    }
    return false;
}

// Setting an attribute replaces the whole policy group, since later tokens
// override earlier ones in the loader.
bool clears_token(std::string_view token, Attr attr) {
    switch (attr) {
    case Attr::Gen:
        return is_attr_token(token, Attr::Gen);
    case Attr::Txt:
    case Attr::Bin:
        return token == "txt" || token == "-txt" || token == "bin" || token == "-bin";
    case Attr::Lf:
    case Attr::Crlf:
    case Attr::Cr:
        return token == "eol:lf" || token == "eol:crlf" || token == "eol:cr" || token == "-eol";
    }
    return false;
}

struct Line {
    std::string text;
    std::string eol;
    bool is_rule = false;
    std::string pattern;
    std::vector<std::string> attrs;
};

std::vector<Line> parse_lines(std::string_view data) {
    std::vector<Line> lines;
    std::size_t start = 0;
    while (start < data.size()) {
        const std::size_t newline = data.find('\n', start);
        Line line;
        if (newline == std::string_view::npos) {
            line.text = std::string(data.substr(start));
            start = data.size();
        } else {
            std::string_view body = data.substr(start, newline - start);
            if (!body.empty() && body.back() == '\r') {
                body.remove_suffix(1);
                line.eol = "\r\n";
            } else {
                line.eol = "\n";
            }
            line.text = std::string(body);
            start = newline + 1;
        }
        const std::string_view trimmed = attr_trim(line.text);
        if (!trimmed.empty() && trimmed.front() != '#') {
            auto tokens = tokenize(trimmed);
            if (!tokens.empty()) {
                line.is_rule = true;
                line.pattern = std::move(tokens.front());
                for (std::size_t i = 1; i < tokens.size(); ++i)
                    line.attrs.push_back(std::move(tokens[i]));
            }
        }
        lines.push_back(std::move(line));
    }
    return lines;
}

std::string canonical_line(const Line& line) {
    std::string out = line.pattern;
    for (const auto& attr : line.attrs) {
        out.push_back(' ');
        out += attr;
    }
    return out;
}

std::string serialize(const std::vector<Line>& lines, const std::vector<bool>& removed) {
    std::vector<std::size_t> kept;
    kept.reserve(lines.size());
    for (std::size_t i = 0; i < lines.size(); ++i) {
        if (i < removed.size() && removed[i])
            continue;
        kept.push_back(i);
    }
    std::string out;
    for (std::size_t i = 0; i < kept.size(); ++i) {
        const Line& line = lines[kept[i]];
        out += line.is_rule ? canonical_line(line) : line.text;
        if (i + 1 < kept.size())
            out += line.eol.empty() ? "\n" : line.eol;
        else
            out += line.eol;
    }
    if (!out.empty() && out.back() != '\n')
        out.push_back('\n');
    return out;
}

std::optional<std::vector<std::string>> collect_operands(const std::vector<std::string>& args,
                                                         std::size_t start) {
    std::vector<std::string> operands;
    bool end_flags = false;
    for (std::size_t i = start; i < args.size(); ++i) {
        const std::string& arg = args[i];
        if (!end_flags && arg == "--") {
            end_flags = true;
        } else if (!end_flags && attr_is_flag(arg)) {
            error_prefix();
            std::cout << "unknown flag: " << arg << "\n";
            return std::nullopt;
        } else {
            operands.push_back(arg);
        }
    }
    return operands;
}

std::optional<std::vector<std::string>> normalize_patterns(const fs::path& root,
                                                           const std::vector<std::string>& args) {
    const auto cwd_rel = cwd_relative(root);
    if (!cwd_rel) {
        error_prefix();
        std::cout << "cannot determine current directory\n";
        return std::nullopt;
    }
    std::vector<std::string> patterns;
    for (const auto& arg : args) {
        auto norm = pathspec_normalize(root, *cwd_rel, arg);
        if (!norm || norm->empty() || !valid_path(*norm) ||
            norm->find_first_of(" \t\r\n") != std::string::npos || norm->front() == '#') {
            error_prefix();
            std::cout << arg << "\n";
            std::cout << "not a valid attribute pattern\n";
            return std::nullopt;
        }
        patterns.push_back(std::move(*norm));
    }
    return patterns;
}

int attr_set(Attr attr, const std::vector<std::string>& args) {
    const auto operands = collect_operands(args, 3);
    if (!operands)
        return 1;
    if (operands->empty()) {
        error_prefix();
        std::cout << "attr " << canonical_token(attr) << " requires at least one glob\n";
        return 1;
    }
    const auto root = discover_repo(".");
    if (!root) {
        error_prefix();
        std::cout << "not a veins repository\n";
        return 1;
    }
    const auto patterns = normalize_patterns(*root, *operands);
    if (!patterns)
        return 1;

    const fs::path path = *root / ".vnattribs";
    std::string data;
    if (!load_attribs(path, data))
        return 1;
    std::vector<Line> lines = parse_lines(data);

    std::size_t changed = 0;
    for (const auto& pattern : *patterns) {
        std::optional<std::size_t> target;
        for (std::size_t i = 0; i < lines.size(); ++i) {
            if (lines[i].is_rule && lines[i].pattern == pattern)
                target = i;
        }
        std::vector<std::string> attrs;
        if (target) {
            for (const auto& token : lines[*target].attrs) {
                if (!clears_token(token, attr))
                    attrs.push_back(token);
            }
        }
        attrs.emplace_back(canonical_token(attr));
        if (target) {
            if (lines[*target].attrs == attrs)
                continue;
            lines[*target].attrs = std::move(attrs);
        } else {
            Line line;
            line.is_rule = true;
            line.pattern = pattern;
            line.attrs = std::move(attrs);
            line.eol = "\n";
            if (!lines.empty() && lines.back().eol.empty())
                lines.back().eol = "\n";
            lines.push_back(std::move(line));
        }
        ++changed;
    }

    if (changed == 0) {
        info_prefix();
        std::cout << "no new attribute rules\n";
        return 0;
    }
    if (!write_atomic(path, bytes_of(serialize(lines, {})))) {
        error_prefix();
        std::cout << "cannot write .vnattribs\n";
        return 1;
    }
    info_prefix();
    std::cout << "updated " << changed << " attribute rule(s)\n";
    return 0;
}

int attr_remove(const std::vector<std::string>& args) {
    auto operands = collect_operands(args, 3);
    if (!operands)
        return 1;
    if (operands->size() < 2) {
        error_prefix();
        std::cout << "usage: vn attr rm <gen|txt|bin|lf|crlf|cr> <glob>...\n";
        return 1;
    }
    const auto attr = parse_attr(operands->front());
    if (!attr) {
        error_prefix();
        std::cout << "unknown attribute: " << operands->front() << "\n";
        return 1;
    }
    operands->erase(operands->begin());

    const auto root = discover_repo(".");
    if (!root) {
        error_prefix();
        std::cout << "not a veins repository\n";
        return 1;
    }
    const auto patterns = normalize_patterns(*root, *operands);
    if (!patterns)
        return 1;

    const fs::path path = *root / ".vnattribs";
    std::string data;
    if (!load_attribs(path, data))
        return 1;
    std::vector<Line> lines = parse_lines(data);
    std::vector<bool> removed(lines.size(), false);

    std::size_t changed = 0;
    for (const auto& pattern : *patterns) {
        for (std::size_t i = 0; i < lines.size(); ++i) {
            if (removed[i] || !lines[i].is_rule || lines[i].pattern != pattern)
                continue;
            std::vector<std::string> attrs;
            for (const auto& token : lines[i].attrs) {
                if (!is_attr_token(token, *attr))
                    attrs.push_back(token);
            }
            if (attrs.size() == lines[i].attrs.size())
                continue;
            if (attrs.empty())
                removed[i] = true;
            else
                lines[i].attrs = std::move(attrs);
            ++changed;
        }
    }

    if (changed == 0) {
        info_prefix();
        std::cout << "no matching attribute rules\n";
        return 0;
    }
    if (!write_atomic(path, bytes_of(serialize(lines, removed)))) {
        error_prefix();
        std::cout << "cannot write .vnattribs\n";
        return 1;
    }
    info_prefix();
    std::cout << "removed " << changed << " attribute rule(s)\n";
    return 0;
}

int attr_list(const std::vector<std::string>& args) {
    const auto operands = collect_operands(args, 3);
    if (!operands)
        return 1;
    if (!operands->empty()) {
        error_prefix();
        std::cout << "usage: vn attr ls\n";
        return 1;
    }
    const auto root = discover_repo(".");
    if (!root) {
        error_prefix();
        std::cout << "not a veins repository\n";
        return 1;
    }
    std::string data;
    if (!load_attribs(*root / ".vnattribs", data))
        return 1;
    for (const auto& line : parse_lines(data)) {
        if (line.is_rule)
            std::cout << canonical_line(line) << "\n";
    }
    return 0;
}

} // namespace

int attr_run(const std::vector<std::string>& args) {
    if (args.size() < 3) {
        error_prefix();
        std::cout << "attr requires a subcommand\n";
        std::cout << "run 'vn help attr' for details\n";
        return 1;
    }
    const std::string& sub = args[2];
    if (sub == "ls")
        return attr_list(args);
    if (sub == "rm")
        return attr_remove(args);
    if (const auto attr = parse_attr(sub))
        return attr_set(*attr, args);
    error_prefix();
    std::cout << "unknown attr subcommand: " << sub << "\n";
    return 1;
}

} // namespace vn