navid/veins / 46f2c49a75178c33115126e2be586d86fb892e95a42b5b8b9eaf09068fb6c666 / xveins/src/remove.cpp

remove.cpp

← xveins/src · 11017 bytes · raw · download

#include "local_commands.h"

#include "pathspec.h"
#include "store.h"
#include "worktree.h"

#include <algorithm>
#include <iostream>
#include <set>
#include <system_error>

namespace vn {

namespace {

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

bool starts_with_child(std::string_view path, std::string_view parent) {
  return path.size() > parent.size() &&
         path.compare(0, parent.size(), parent) == 0 &&
         path[parent.size()] == '/';
}

bool literal_matches(std::string_view operand, std::string_view path) {
  return path == operand || starts_with_child(path, operand);
}

bool glob_matches(std::string_view operand, std::string_view path) {
  if (glob_match(operand, path))
    return true;
  for (std::size_t i = 0; i < path.size(); ++i) {
    if (path[i] == '/' && glob_match(operand, path.substr(0, i)))
      return true;
  }
  return false;
}

bool operand_matches(std::string_view operand, std::string_view path) {
  if (pathspec_has_glob(operand))
    return glob_matches(operand, path);
  return literal_matches(operand, path);
}

bool subtree_affected(std::string_view prefix,
                      const std::vector<std::string> &removes) {
  if (prefix.empty())
    return !removes.empty();
  for (const auto &r : removes) {
    if (prefix == r || starts_with_child(r, prefix) ||
        starts_with_child(prefix, r))
      return true;
  }
  return false;
}

bool path_removed(std::string_view path,
                  const std::vector<std::string> &removes) {
  for (const auto &r : removes) {
    if (path == r || starts_with_child(path, r))
      return true;
  }
  return false;
}

std::string join_path(std::string_view prefix, std::string_view name) {
  if (prefix.empty())
    return std::string(name);
  std::string out(prefix);
  out.push_back('/');
  out.append(name);
  return out;
}

Id empty_tree_id(Txn &tx) {
  auto body = encode_tree({});
  if (!body)
    return Id{};
  return tx.add_object(TYPE_TREE, *body);
}

std::optional<Id> filter_tree(Txn &tx, Store &store, const Id &tree_id,
                              std::string_view prefix,
                              const std::vector<std::string> &removes,
                              std::size_t depth) {
  if (depth > 4096)
    return tree_id;
  if (!subtree_affected(prefix, removes))
    return tree_id;
  auto body = store.read_body(tree_id, TYPE_TREE);
  if (!body)
    return tree_id;
  auto tree = decode_tree(bytes_of(*body));
  if (!tree)
    return tree_id;

  std::vector<TreeEntry> entries;
  entries.reserve(tree->entries.size());
  for (const auto &entry : tree->entries) {
    const std::string full = join_path(prefix, entry.name);
    if (path_removed(full, removes))
      continue;
    if (entry.kind == KIND_SUBTREE && subtree_affected(full, removes)) {
      auto child = filter_tree(tx, store, entry.target, full, removes, depth + 1);
      if (child)
        entries.push_back(TreeEntry{entry.name, entry.kind, *child});
    } else {
      entries.push_back(entry);
    }
  }
  if (entries.empty())
    return std::nullopt;
  auto encoded = encode_tree(entries);
  if (!encoded)
    return std::nullopt;
  return tx.add_object(TYPE_TREE, *encoded);
}

std::optional<std::string> parent_of(std::string_view path) {
  const auto slash = path.rfind('/');
  if (slash == std::string_view::npos)
    return std::nullopt;
  return std::string(path.substr(0, slash));
}

bool delete_one(const fs::path &root, std::string_view rel) {
  std::error_code ec;
  const fs::path full = root / path_from_bytes(rel);
  const bool removed = fs::remove(full, ec);
  return removed && !ec;
}

void prune_empty_parents(const fs::path &root, std::string_view rel) {
  std::string current(rel);
  for (;;) {
    const auto slash = current.rfind('/');
    if (slash == std::string::npos)
      break;
    current.resize(slash);
    std::error_code ec;
    const fs::path dir = root / path_from_bytes(current);
    if (!fs::is_directory(dir, ec))
      break;
    if (!fs::remove(dir, ec) || ec)
      break;
  }
}

int delete_paths(const fs::path &root, const std::vector<std::string> &removes) {
  std::size_t failed = 0;
  for (const auto &rel : removes) {
    if (!delete_one(root, rel))
      ++failed;
    else
      prune_empty_parents(root, rel);
  }
  if (failed > 0) {
    warning_prefix();
    std::cout << "could not delete " << failed << " path(s) from disk\n";
    return 1;
  }
  return 0;
}

int run_removal(const fs::path &root, const std::vector<std::string> &operands,
                bool delete_mode) {
  Store store = Store::open_all(root);
  auto tx = Txn::begin(root, store);
  if (!tx) {
    error_prefix();
    std::cout << "cannot load repository state\n";
    return 1;
  }
  const auto wc = working_copy_id(tx->view());
  if (!wc) {
    error_prefix();
    std::cout << "no working-copy commit\n";
    return 1;
  }
  auto loaded = load_commit(store, *wc);
  if (!loaded) {
    error_prefix();
    std::cout << "cannot read working-copy commit\n";
    return 1;
  }

  std::vector<bool> matched(operands.size(), false);
  std::vector<std::string> removes;
  std::set<std::string> seen;
  for (const auto &entry : flatten_tree(store, loaded->commit.root_tree)) {
    for (std::size_t i = 0; i < operands.size(); ++i) {
      if (operand_matches(operands[i], entry.path)) {
        matched[i] = true;
        if (seen.insert(entry.path).second)
          removes.push_back(entry.path);
      }
    }
  }

  bool unmatched = false;
  for (std::size_t i = 0; i < operands.size(); ++i) {
    if (!matched[i]) {
      error_prefix();
      std::cout << "path is not tracked: " << operands[i] << "\n";
      unmatched = true;
    }
  }
  if (unmatched)
    return 1;

  if (!delete_mode) {
    for (const auto &rel : removes) {
      if (!ignore_path_ignored(root, rel)) {
        warning_prefix();
        std::cout << rel
                  << " is not ignored and will be re-added on the next snapshot\n";
      }
    }
  }

  auto new_root = filter_tree(*tx, store, loaded->commit.root_tree, "", removes, 0);
  Id root_id{};
  if (new_root)
    root_id = *new_root;
  else
    root_id = empty_tree_id(*tx);
  if (std::memcmp(root_id.data(), loaded->commit.root_tree.data(), ID_LEN) == 0) {
    error_prefix();
    std::cout << "no tracked paths to remove\n";
    return 1;
  }

  const Sig sig = identity_signature(root);
  Commit commit = loaded->commit;
  commit.root_tree = root_id;
  commit.committer = sig;
  commit.renames_state = RENAMES_RECORDED;
  commit.renames.clear();
  const Id new_id = tx->add_object(TYPE_COMMIT, encode_commit(commit));

  remove_head(tx->view(), *wc);
  move_bookmarks(tx->view(), *wc, new_id);
  set_workspace(tx->view(), new_id);
  rebuild_heads(tx->view());

  int status = 0;
  const auto finished = tx->finish("rm");
  if (!finished)
    status = 1;
  if (status == 0)
    (void)mark_native(root, new_id);

  if (status == 0) {
    if (delete_mode) {
      const int del = delete_paths(root, removes);
      if (del != 0)
        status = del;
    }
    info_prefix();
    std::cout << "untracked " << removes.size() << " path(s)\n";
  }
  return status;
}

int rm_command(const std::vector<std::string> &args, std::size_t start) {
  bool delete_mode = false;
  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 && arg == "-delete") {
      delete_mode = true;
    } else if (!end_flags && rm_is_flag(arg)) {
      error_prefix();
      std::cout << "unknown flag: " << arg << "\n";
      return 1;
    } else {
      operands.push_back(arg);
    }
  }
  if (operands.empty()) {
    error_prefix();
    std::cout << "rm requires at least one path\n";
    return 1;
  }

  const auto root = discover_repo(".");
  if (!root) {
    error_prefix();
    std::cout << "not a veins repository\n";
    return 1;
  }
  const int snap = snapshot_run(*root);
  if (snap != 0)
    return snap;

  const auto cwd_rel = cwd_relative(*root);
  if (!cwd_rel) {
    error_prefix();
    std::cout << "cannot determine current directory\n";
    return 1;
  }

  std::vector<std::string> normalized;
  for (const auto &arg : operands) {
    auto norm = pathspec_normalize(*root, *cwd_rel, arg);
    if (!norm) {
      error_prefix();
      std::cout << "path is outside the repository: " << arg << "\n";
      return 1;
    }
    if (norm->empty() || !valid_path(*norm)) {
      error_prefix();
      std::cout << "invalid path: " << arg << "\n";
      return 1;
    }
    normalized.push_back(std::move(*norm));
  }
  if (normalized.empty()) {
    error_prefix();
    std::cout << "rm requires at least one path\n";
    return 1;
  }
  return run_removal(*root, normalized, delete_mode);
}

} // namespace

int rm_run(const std::vector<std::string> &args) { return rm_command(args, 2); }

int mv_run(const std::vector<std::string> &args) {
  std::vector<std::string> operands;
  bool end_flags = false;
  for (std::size_t i = 2; i < args.size(); ++i) {
    const std::string &arg = args[i];
    if (!end_flags && arg == "--") {
      end_flags = true;
    } else if (!end_flags && rm_is_flag(arg)) {
      error_prefix();
      std::cout << "unknown flag: " << arg << "\n";
      return 1;
    } else {
      operands.push_back(arg);
    }
  }

  const auto root = discover_repo(".");
  if (!root) {
    error_prefix();
    std::cout << "not a veins repository\n";
    return 1;
  }
  const int snap = snapshot_run(*root);
  if (snap != 0)
    return snap;

  if (operands.size() != 2) {
    error_prefix();
    std::cout << "mv requires a source and a destination\n";
    return 1;
  }

  const auto cwd_rel = cwd_relative(*root);
  if (!cwd_rel) {
    error_prefix();
    std::cout << "cannot determine current directory\n";
    return 1;
  }
  auto src = pathspec_normalize(*root, *cwd_rel, operands[0]);
  if (!src) {
    error_prefix();
    std::cout << "invalid path\n";
    return 1;
  }
  auto dst = pathspec_normalize(*root, *cwd_rel, operands[1]);
  if (!dst) {
    error_prefix();
    std::cout << "invalid path\n";
    return 1;
  }

  const fs::path src_abs = *root / path_from_bytes(*src);
  const fs::path dst_abs = *root / path_from_bytes(*dst);
  if (!stat_path(src_abs)) {
    error_prefix();
    std::cout << "not a tracked path: " << *src << "\n";
    return 1;
  }
  if (stat_path(dst_abs)) {
    error_prefix();
    std::cout << "destination already exists: " << *dst << "\n";
    return 1;
  }

  if (const auto parent = parent_of(*dst)) {
    if (!ensure_directory(*root / path_from_bytes(*parent))) {
      error_prefix();
      std::cout << "cannot create destination directory\n";
      return 1;
    }
  }
  std::error_code ec;
  fs::rename(src_abs, dst_abs, ec);
  if (ec) {
    error_prefix();
    std::cout << "cannot move path\n";
    return 1;
  }
  return snapshot_run(*root);
}

} // namespace vn