view rust/rhg/src/utils/path_utils.rs @ 48178:f12a19d03d2c

fix: reduce number of tool executions By grouping together (path, ctx) pairs according to the inputs they would provide to fixer tools, we can deduplicate executions of fixer tools to significantly reduce the amount of time spent running slow tools. This change does not handle clean files in the working copy, which could still be deduplicated against the files in the checked out commit. It's a little harder to do that because the filerev is not available in the workingfilectx (and it doesn't exist for added files). Anecdotally, this change makes some real uses cases at Google 10x faster. I think we were originally hesitant to do this because the benefits weren't obvious, and implementing it efficiently is kind of tricky. If we simply memoized the formatter execution function, we would be keeping tons of file content in memory. Also included is a regression test for a corner case that I broke with my first attempt at optimizing this code. Differential Revision: https://phab.mercurial-scm.org/D11280
author Danny Hooper <hooper@google.com>
date Thu, 02 Sep 2021 14:08:45 -0700
parents 9ecf802b06e0
children 10c32e1b892a
line wrap: on
line source

// path utils module
//
// This software may be used and distributed according to the terms of the
// GNU General Public License version 2 or any later version.

use crate::error::CommandError;
use crate::ui::UiError;
use hg::repo::Repo;
use hg::utils::current_dir;
use hg::utils::files::{get_bytes_from_path, relativize_path};
use hg::utils::hg_path::HgPath;
use hg::utils::hg_path::HgPathBuf;
use std::borrow::Cow;

pub fn relativize_paths(
    repo: &Repo,
    paths: impl IntoIterator<Item = impl AsRef<HgPath>>,
    mut callback: impl FnMut(Cow<[u8]>) -> Result<(), UiError>,
) -> Result<(), CommandError> {
    let cwd = current_dir()?;
    let repo_root = repo.working_directory_path();
    let repo_root = cwd.join(repo_root); // Make it absolute
    let repo_root_hgpath =
        HgPathBuf::from(get_bytes_from_path(repo_root.to_owned()));
    let outside_repo: bool;
    let cwd_hgpath: HgPathBuf;

    if let Ok(cwd_relative_to_repo) = cwd.strip_prefix(&repo_root) {
        // The current directory is inside the repo, so we can work with
        // relative paths
        outside_repo = false;
        cwd_hgpath =
            HgPathBuf::from(get_bytes_from_path(cwd_relative_to_repo));
    } else {
        outside_repo = true;
        cwd_hgpath = HgPathBuf::from(get_bytes_from_path(cwd));
    }

    for file in paths {
        if outside_repo {
            let file = repo_root_hgpath.join(file.as_ref());
            callback(relativize_path(&file, &cwd_hgpath))?;
        } else {
            callback(relativize_path(file.as_ref(), &cwd_hgpath))?;
        }
    }
    Ok(())
}