pub struct ShellWriter<W: Write> { /* private fields */ }
Expand description

A writer of var=value pairs.

See ShellWriter::new().

Implementations§

Create a new ShellWriter. The prefix will be prepended anytime a var is outputted, e.g. prefixvar=value.

Generally, you will want to use this like:

use git_status_vars::ShellWriter;
ShellWriter::default().group("group").write_var("var", "value");
// or...
let mut buffer: Vec<u8> = vec![];
ShellWriter::new(&mut buffer, "").group("group").write_var("var", "value");
assert_eq!(buffer, b"group_var=value\n");
Examples found in repository?
src/shell_writer.rs (line 91)
90
91
92
93
94
95
96
97
98
99
    pub fn with_prefix(prefix: String) -> Self {
        Self::new(io::stdout(), prefix)
    }
}

impl Default for ShellWriter<io::Stdout> {
    /// Create a new `ShellWriter` for [`io::stdout()`] and no prefix.
    fn default() -> Self {
        Self::new(io::stdout(), "")
    }

Write var=value. value will be turned into a string, then quoted for safe shell insertion. var will be assumed to be a valid name for a shell variable.

Examples found in repository?
src/lib.rs (line 65)
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
    fn write_to_shell<W: io::Write>(&self, out: &ShellWriter<W>) {
        out.write_var("name", &self.name);
        out.write_var("short", self.short());
        out.write_var("kind", &self.kind);
        out.write_var("error", &self.error);
    }
}

/// The trail of a `HEAD` reference.
#[derive(Debug, Default)]
pub struct Head {
    pub trail: Vec<Reference>,
    pub hash: String,
    pub ahead_of_upstream: Option<usize>,
    pub behind_upstream: Option<usize>,
    pub upstream_error: String,
}

impl ShellVars for Head {
    fn write_to_shell<W: io::Write>(&self, out: &ShellWriter<W>) {
        out.write_var("ref_length", self.trail.len() - 1);
        for (i, reference) in self.trail[1..].iter().enumerate() {
            out.group_n("ref", i + 1).write_vars(reference);
        }
        out.write_var("hash", &self.hash);
        out.write_var("ahead", display_option(self.ahead_of_upstream));
        out.write_var("behind", display_option(self.behind_upstream));
        out.write_var("upstream_error", &self.upstream_error);
    }
}

/// Summarize information about a repository.
///
/// This takes the `Result` from one of the `Repository::open()` functions.
///
/// ### Example
///
/// ```no_run
/// use git_status_vars::{summarize_repository, ShellWriter};
/// use git2::Repository;
///
/// summarize_repository(&ShellWriter::default(), Repository::open_from_env());
/// ```
pub fn summarize_repository<W: std::io::Write>(
    out: &ShellWriter<W>,
    opened: Result<Repository, git2::Error>,
) {
    let result = match opened {
        Ok(repository) => summarize_opened_repository(out, repository),
        Err(error)
            if error.code() == ErrorCode::NotFound
                && error.class() == ErrorClass::Repository =>
        {
            out.write_var("repo_state", "NotFound");
            Ok(())
        }
        Err(error) => Err(error),
    };

    if let Err(error) = result {
        out.write_var("repo_state", "Error");
        out.write_var_debug("repo_error", error);
    }
}

/// Summarize information about a successfully opened repository.
///
/// ### Example
///
/// ```no_run
/// use git_status_vars::{summarize_opened_repository, ShellWriter};
/// use git2::Repository;
///
/// summarize_opened_repository(
///     &ShellWriter::default(),
///     Repository::open_from_env().unwrap(),
/// ).unwrap();
/// ```
pub fn summarize_opened_repository<W: std::io::Write>(
    out: &ShellWriter<W>,
    repository: Repository,
) -> Result<(), git2::Error> {
    out.write_var_debug("repo_state", repository.state());
    out.write_var(
        "repo_workdir",
        display_option(repository.workdir().map(|path| path.display())),
    );
    out.write_var("repo_empty", repository.is_empty()?);
    out.write_var("repo_bare", repository.is_bare());
    out.group("head").write_vars(&head_info(&repository)?);
    out.write_vars(&count_changes(&repository)?);

    Ok(())
}

/// Trace the `HEAD` reference for a repository.
pub fn head_info(repository: &Repository) -> Result<Head, git2::Error> {
    let mut current = "HEAD".to_string();
    let mut head = Head::default();
    loop {
        match repository.find_reference(&current) {
            Ok(reference) => match reference.kind() {
                Some(ReferenceType::Direct) => {
                    head.trail.push(Reference::direct(&display_option(
                        reference.name(),
                    )));
                    head.hash = display_option(reference.target());
                    break;
                }
                Some(ReferenceType::Symbolic) => {
                    head.trail.push(Reference::symbolic(&display_option(
                        reference.name(),
                    )));
                    let target = reference
                        .symbolic_target()
                        .expect("Symbolic ref should have symbolic target");
                    current = target.to_string();
                }
                None => {
                    head.trail.push(Reference::new(
                        display_option(reference.name()),
                        "unknown",
                    ));
                    break;
                }
            },
            Err(error) => {
                head.trail
                    .push(Reference::new_with_error(current, "", error));
                break;
            }
        };
    }

    match get_upstream_difference(repository) {
        Ok(Some((ahead, behind))) => {
            head.ahead_of_upstream = Some(ahead);
            head.behind_upstream = Some(behind);
        }
        Ok(None) => {}
        Err(error) => {
            head.upstream_error = format!("{:?}", error);
        }
    }

    Ok(head)
}

/// Get the (ahead, behind) count of HEAD versus its upstream branch.
pub fn get_upstream_difference(
    repository: &Repository,
) -> Result<Option<(usize, usize)>, git2::Error> {
    let local_ref = repository.head()?.resolve()?;
    if let Some(local_oid) = local_ref.target() {
        let upstream_branch = Branch::wrap(local_ref).upstream()?;
        if let Some(upstream_oid) = upstream_branch.get().target() {
            repository
                .graph_ahead_behind(local_oid, upstream_oid)
                .map(Some)
        } else {
            Ok(None)
        }
    } else {
        Ok(None)
    }
}

fn display_option(s: Option<impl fmt::Display>) -> String {
    s.map(|s| s.to_string()).unwrap_or_else(|| "".to_string())
}

/// Track changes in the working tree and index (staged area).
#[derive(Debug, Default)]
pub struct ChangeCounters {
    pub untracked: usize,
    pub unstaged: usize,
    pub staged: usize,
    pub conflicted: usize,
}

impl From<[usize; 4]> for ChangeCounters {
    fn from(array: [usize; 4]) -> Self {
        ChangeCounters {
            untracked: array[0],
            unstaged: array[1],
            staged: array[2],
            conflicted: array[3],
        }
    }
}

impl ShellVars for ChangeCounters {
    // Output the tree change information with a prefix (e.g. "tree_").
    fn write_to_shell<W: io::Write>(&self, out: &ShellWriter<W>) {
        out.write_var("untracked_count", self.untracked);
        out.write_var("unstaged_count", self.unstaged);
        out.write_var("staged_count", self.staged);
        out.write_var("conflicted_count", self.conflicted);
    }

Write var=value. value will be formatted into a string using Debug, then quoted for safe shell insertion. var will be assumed to be a valid name for a shell variable.

Examples found in repository?
src/lib.rs (line 125)
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
pub fn summarize_repository<W: std::io::Write>(
    out: &ShellWriter<W>,
    opened: Result<Repository, git2::Error>,
) {
    let result = match opened {
        Ok(repository) => summarize_opened_repository(out, repository),
        Err(error)
            if error.code() == ErrorCode::NotFound
                && error.class() == ErrorClass::Repository =>
        {
            out.write_var("repo_state", "NotFound");
            Ok(())
        }
        Err(error) => Err(error),
    };

    if let Err(error) = result {
        out.write_var("repo_state", "Error");
        out.write_var_debug("repo_error", error);
    }
}

/// Summarize information about a successfully opened repository.
///
/// ### Example
///
/// ```no_run
/// use git_status_vars::{summarize_opened_repository, ShellWriter};
/// use git2::Repository;
///
/// summarize_opened_repository(
///     &ShellWriter::default(),
///     Repository::open_from_env().unwrap(),
/// ).unwrap();
/// ```
pub fn summarize_opened_repository<W: std::io::Write>(
    out: &ShellWriter<W>,
    repository: Repository,
) -> Result<(), git2::Error> {
    out.write_var_debug("repo_state", repository.state());
    out.write_var(
        "repo_workdir",
        display_option(repository.workdir().map(|path| path.display())),
    );
    out.write_var("repo_empty", repository.is_empty()?);
    out.write_var("repo_bare", repository.is_bare());
    out.group("head").write_vars(&head_info(&repository)?);
    out.write_vars(&count_changes(&repository)?);

    Ok(())
}

Write an object with the ShellVars trait. Mostly used with Self::group() and Self::group_n().

Examples found in repository?
src/lib.rs (line 86)
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
    fn write_to_shell<W: io::Write>(&self, out: &ShellWriter<W>) {
        out.write_var("ref_length", self.trail.len() - 1);
        for (i, reference) in self.trail[1..].iter().enumerate() {
            out.group_n("ref", i + 1).write_vars(reference);
        }
        out.write_var("hash", &self.hash);
        out.write_var("ahead", display_option(self.ahead_of_upstream));
        out.write_var("behind", display_option(self.behind_upstream));
        out.write_var("upstream_error", &self.upstream_error);
    }
}

/// Summarize information about a repository.
///
/// This takes the `Result` from one of the `Repository::open()` functions.
///
/// ### Example
///
/// ```no_run
/// use git_status_vars::{summarize_repository, ShellWriter};
/// use git2::Repository;
///
/// summarize_repository(&ShellWriter::default(), Repository::open_from_env());
/// ```
pub fn summarize_repository<W: std::io::Write>(
    out: &ShellWriter<W>,
    opened: Result<Repository, git2::Error>,
) {
    let result = match opened {
        Ok(repository) => summarize_opened_repository(out, repository),
        Err(error)
            if error.code() == ErrorCode::NotFound
                && error.class() == ErrorClass::Repository =>
        {
            out.write_var("repo_state", "NotFound");
            Ok(())
        }
        Err(error) => Err(error),
    };

    if let Err(error) = result {
        out.write_var("repo_state", "Error");
        out.write_var_debug("repo_error", error);
    }
}

/// Summarize information about a successfully opened repository.
///
/// ### Example
///
/// ```no_run
/// use git_status_vars::{summarize_opened_repository, ShellWriter};
/// use git2::Repository;
///
/// summarize_opened_repository(
///     &ShellWriter::default(),
///     Repository::open_from_env().unwrap(),
/// ).unwrap();
/// ```
pub fn summarize_opened_repository<W: std::io::Write>(
    out: &ShellWriter<W>,
    repository: Repository,
) -> Result<(), git2::Error> {
    out.write_var_debug("repo_state", repository.state());
    out.write_var(
        "repo_workdir",
        display_option(repository.workdir().map(|path| path.display())),
    );
    out.write_var("repo_empty", repository.is_empty()?);
    out.write_var("repo_bare", repository.is_bare());
    out.group("head").write_vars(&head_info(&repository)?);
    out.write_vars(&count_changes(&repository)?);

    Ok(())
}

Generate a sub-writer with this group name. Example output:

prefix_group_var=value
Examples found in repository?
src/shell_writer.rs (line 84)
79
80
81
82
83
84
85
    pub fn group_n(
        &self,
        prefix: impl Display,
        n: impl Display,
    ) -> ShellWriter<W> {
        self.group(format!("{}{}", prefix, n))
    }
More examples
Hide additional examples
src/lib.rs (line 153)
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
pub fn summarize_opened_repository<W: std::io::Write>(
    out: &ShellWriter<W>,
    repository: Repository,
) -> Result<(), git2::Error> {
    out.write_var_debug("repo_state", repository.state());
    out.write_var(
        "repo_workdir",
        display_option(repository.workdir().map(|path| path.display())),
    );
    out.write_var("repo_empty", repository.is_empty()?);
    out.write_var("repo_bare", repository.is_bare());
    out.group("head").write_vars(&head_info(&repository)?);
    out.write_vars(&count_changes(&repository)?);

    Ok(())
}

Generate a sub-writer with this group name and number. Example output:

prefix_groupN_var=value
Examples found in repository?
src/lib.rs (line 86)
83
84
85
86
87
88
89
90
91
92
    fn write_to_shell<W: io::Write>(&self, out: &ShellWriter<W>) {
        out.write_var("ref_length", self.trail.len() - 1);
        for (i, reference) in self.trail[1..].iter().enumerate() {
            out.group_n("ref", i + 1).write_vars(reference);
        }
        out.write_var("hash", &self.hash);
        out.write_var("ahead", display_option(self.ahead_of_upstream));
        out.write_var("behind", display_option(self.behind_upstream));
        out.write_var("upstream_error", &self.upstream_error);
    }

Create a new ShellWriter for io::stdout() and a prefix.

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more

Create a new ShellWriter for io::stdout() and no prefix.

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.