Skip to content

gix index entries with attributes listing #830

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 18 commits into from
Apr 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,16 +83,16 @@ is usable to some extent.
* [gix-command](https://github.com/Byron/gitoxide/blob/main/crate-status.md#gix-command)
* [gix-prompt](https://github.com/Byron/gitoxide/blob/main/crate-status.md#gix-prompt)
* [gix-refspec](https://github.com/Byron/gitoxide/blob/main/crate-status.md#gix-refspec)
* `gitoxide-core`
* **very early** _(possibly without any documentation and many rough edges)_
* [gix-utils](https://github.com/Byron/gitoxide/blob/main/crate-status.md#gix-utils)
* [gix-fs](https://github.com/Byron/gitoxide/blob/main/crate-status.md#gix-fs)
* [gix-utils](https://github.com/Byron/gitoxide/blob/main/crate-status.md#gix-utils)
* [gix-hashtable](https://github.com/Byron/gitoxide/blob/main/crate-status.md#gix-hashtable)
* [gix-worktree](https://github.com/Byron/gitoxide/blob/main/crate-status.md#gix-worktree)
* [gix-bitmap](https://github.com/Byron/gitoxide/blob/main/crate-status.md#gix-bitmap)
* `gitoxide-core`
* **very early** _(possibly without any documentation and many rough edges)_
* [gix-date](https://github.com/Byron/gitoxide/blob/main/crate-status.md#gix-date)
* [gix-hashtable](https://github.com/Byron/gitoxide/blob/main/crate-status.md#gix-hashtable)
* **idea** _(just a name placeholder)_
* [gix-archive](https://github.com/Byron/gitoxide/blob/main/crate-status.md#gix-archive)
* **idea** _(just a name placeholder)_
* [gix-note](https://github.com/Byron/gitoxide/blob/main/crate-status.md#gix-note)
* [gix-fetchhead](https://github.com/Byron/gitoxide/blob/main/crate-status.md#gix-fetchhead)
* [gix-filter](https://github.com/Byron/gitoxide/blob/main/crate-status.md#gix-filter)
Expand Down
2 changes: 1 addition & 1 deletion crate-status.md
Original file line number Diff line number Diff line change
Expand Up @@ -690,7 +690,7 @@ See its [README.md](https://github.com/Byron/gitoxide/blob/main/gix-lock/README.
* [x] proper handling of worktree related refs
* [ ] create, move, remove, and repair
* [x] access exclude information
* [ ] access attribute information
* [x] access attribute information
* [x] respect `core.worktree` configuration
- **deviation**
* The delicate interplay between `GIT_COMMON_DIR` and `GIT_WORK_TREE` isn't implemented.
Expand Down
94 changes: 0 additions & 94 deletions gitoxide-core/src/index/entries.rs

This file was deleted.

3 changes: 0 additions & 3 deletions gitoxide-core/src/index/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,6 @@ pub struct Options {
pub format: crate::OutputFormat,
}

mod entries;
pub use entries::entries;

pub mod information;

fn parse_file(index_path: impl AsRef<Path>, object_hash: gix::hash::Kind) -> anyhow::Result<gix::index::File> {
Expand Down
13 changes: 7 additions & 6 deletions gitoxide-core/src/repository/exclude.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::io;

use anyhow::{bail, Context};
use anyhow::bail;
use gix::prelude::FindExt;

use crate::OutputFormat;
Expand Down Expand Up @@ -31,11 +31,12 @@ pub fn query(
bail!("JSON output isn't implemented yet");
}

let worktree = repo
.worktree()
.with_context(|| "Cannot check excludes without a current worktree")?;
let index = worktree.index()?;
let mut cache = worktree.excludes(&index, Some(gix::ignore::Search::from_overrides(overrides)))?;
let index = repo.index()?;
let mut cache = repo.excludes(
&index,
Some(gix::ignore::Search::from_overrides(overrides)),
Default::default(),
)?;

let prefix = repo.prefix().expect("worktree - we have an index by now")?;

Expand Down
228 changes: 228 additions & 0 deletions gitoxide-core/src/repository/index/entries.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,228 @@
#[derive(Debug)]
pub struct Options {
pub format: crate::OutputFormat,
/// If true, also show attributes
pub attributes: Option<Attributes>,
pub statistics: bool,
}

#[derive(Debug)]
pub enum Attributes {
/// Look at worktree attributes and index as fallback.
WorktreeAndIndex,
/// Look at attributes from index files only.
Index,
}

pub(crate) mod function {
use crate::repository::index::entries::{Attributes, Options};
use gix::attrs::State;
use gix::bstr::ByteSlice;
use gix::odb::FindExt;
use std::borrow::Cow;
use std::io::{BufWriter, Write};

pub fn entries(
repo: gix::Repository,
out: impl std::io::Write,
mut err: impl std::io::Write,
Options {
format,
attributes,
statistics,
}: Options,
) -> anyhow::Result<()> {
use crate::OutputFormat::*;
let index = repo.index()?;
let mut cache = attributes
.map(|attrs| {
repo.attributes(
&index,
match attrs {
Attributes::WorktreeAndIndex => {
gix::worktree::cache::state::attributes::Source::WorktreeThenIdMapping
}
Attributes::Index => gix::worktree::cache::state::attributes::Source::IdMapping,
},
match attrs {
Attributes::WorktreeAndIndex => {
gix::worktree::cache::state::ignore::Source::WorktreeThenIdMappingIfNotSkipped
}
Attributes::Index => gix::worktree::cache::state::ignore::Source::IdMapping,
},
None,
)
.map(|cache| (cache.attribute_matches(), cache))
})
.transpose()?;
let mut stats = Statistics {
entries: index.entries().len(),
..Default::default()
};

let mut out = BufWriter::new(out);
#[cfg(feature = "serde")]
if let Json = format {
out.write_all(b"[\n")?;
}
let mut entries = index.entries().iter().peekable();
while let Some(entry) = entries.next() {
let attrs = cache
.as_mut()
.map(|(attrs, cache)| {
cache
.at_entry(entry.path(&index), None, |id, buf| repo.objects.find_blob(id, buf))
.map(|entry| {
let is_excluded = entry.is_excluded();
stats.excluded += usize::from(is_excluded);
let attributes: Vec<_> = {
entry.matching_attributes(attrs);
attrs.iter().map(|m| m.assignment.to_owned()).collect()
};
stats.with_attributes += usize::from(!attributes.is_empty());
Attrs {
is_excluded,
attributes,
}
})
})
.transpose()?;
match format {
Human => to_human(&mut out, &index, entry, attrs)?,
#[cfg(feature = "serde")]
Json => to_json(&mut out, &index, entry, attrs, entries.peek().is_none())?,
}
}

#[cfg(feature = "serde")]
if format == Json {
out.write_all(b"]\n")?;
out.flush()?;
if statistics {
serde_json::to_writer_pretty(&mut err, &stats)?;
}
}
if format == Human && statistics {
out.flush()?;
stats.cache = cache.map(|c| *c.1.statistics());
writeln!(err, "{:#?}", stats)?;
}
Ok(())
}

#[cfg_attr(feature = "serde", derive(serde::Serialize))]
struct Attrs {
is_excluded: bool,
attributes: Vec<gix::attrs::Assignment>,
}

#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[derive(Default, Debug)]
struct Statistics {
#[allow(dead_code)] // Not really dead, but Debug doesn't count for it even though it's crucial.
pub entries: usize,
pub excluded: usize,
pub with_attributes: usize,
pub cache: Option<gix::worktree::cache::Statistics>,
}

#[cfg(feature = "serde")]
fn to_json(
mut out: &mut impl std::io::Write,
index: &gix::index::File,
entry: &gix::index::Entry,
attrs: Option<Attrs>,
is_last: bool,
) -> anyhow::Result<()> {
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
struct Entry<'a> {
stat: &'a gix::index::entry::Stat,
hex_id: String,
flags: u32,
mode: u32,
path: std::borrow::Cow<'a, str>,
meta: Option<Attrs>,
}

serde_json::to_writer(
&mut out,
&Entry {
stat: &entry.stat,
hex_id: entry.id.to_hex().to_string(),
flags: entry.flags.bits(),
mode: entry.mode.bits(),
path: entry.path(index).to_str_lossy(),
meta: attrs,
},
)?;

if is_last {
out.write_all(b"\n")?;
} else {
out.write_all(b",\n")?;
}
Ok(())
}

fn to_human(
out: &mut impl std::io::Write,
file: &gix::index::File,
entry: &gix::index::Entry,
attrs: Option<Attrs>,
) -> std::io::Result<()> {
writeln!(
out,
"{} {}{:?} {} {}{}",
match entry.flags.stage() {
0 => "BASE ",
1 => "OURS ",
2 => "THEIRS ",
_ => "UNKNOWN",
},
if entry.flags.is_empty() {
"".to_string()
} else {
format!("{:?} ", entry.flags)
},
entry.mode,
entry.id,
entry.path(file),
attrs
.map(|a| {
let mut buf = String::new();
if a.is_excluded {
buf.push_str(" ❌");
}
if !a.attributes.is_empty() {
buf.push_str(" (");
for assignment in a.attributes {
match assignment.state {
State::Set => {
buf.push_str(assignment.name.as_str());
}
State::Unset => {
buf.push('-');
buf.push_str(assignment.name.as_str());
}
State::Value(v) => {
buf.push_str(assignment.name.as_str());
buf.push('=');
buf.push_str(v.as_ref().as_bstr().to_str_lossy().as_ref());
}
State::Unspecified => {
buf.push('!');
buf.push_str(assignment.name.as_str());
}
}
buf.push_str(", ");
}
buf.pop();
buf.pop();
buf.push(')');
}
buf.into()
})
.unwrap_or(Cow::Borrowed(""))
)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,6 @@ pub fn from_tree(

Ok(())
}

pub mod entries;
pub use entries::function::entries;
Loading