-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathcommit.rs
More file actions
463 lines (438 loc) · 12.9 KB
/
commit.rs
File metadata and controls
463 lines (438 loc) · 12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
use crate::object::{GitObject, ObjectInner};
use crate::repository::Repository;
use crate::signature::{Signature, SignaturePayload};
use crate::tree::{Tree, TreeInner};
use chrono::{DateTime, Utc};
use napi::bindgen_prelude::*;
use napi_derive::napi;
use std::ops::Deref;
#[napi(object)]
pub struct CommitOptions {
pub update_ref: Option<String>,
/// Signature for author.
///
/// If not provided, the default signature of the repository will be used.
/// If there is no default signature set for the repository, an error will occur.
pub author: Option<SignaturePayload>,
/// Signature for commiter.
///
/// If not provided, the default signature of the repository will be used.
/// If there is no default signature set for the repository, an error will occur.
pub committer: Option<SignaturePayload>,
pub parents: Option<Vec<String>>,
/// GPG signature string for signed commits.
///
/// If provided, this will create a signed commit.
pub signature: Option<String>,
/// Custom signature field name.
///
/// If not provided, the default signature field (gpgsig) will be used.
pub signature_field: Option<String>,
}
#[napi(object)]
#[derive(Default)]
pub struct AmendOptions {
/// If not NULL, name of the reference that will be updated to point to this commit.
/// If the reference is not direct, it will be resolved to a direct reference.
/// Use "HEAD" to update the HEAD of the current branch and make it point to this commit.
///
/// If the reference doesn't exist yet, it will be created.
/// If it does exist, the first parent must be the tip of this branch.
pub update_ref: Option<String>,
/// Signature for author.
pub author: Option<SignaturePayload>,
/// Signature for committer.
pub committer: Option<SignaturePayload>,
/// Full message for this commit
pub message: Option<String>,
/// The encoding for the message in the commit, represented with a standard encoding name.
/// E.g. "UTF-8".
/// If NULL, no encoding header is written and UTF-8 is assumed.
pub message_encoding: Option<String>,
}
pub(crate) enum CommitInner {
Repo(SharedReference<Repository, git2::Commit<'static>>),
Owned(git2::Commit<'static>),
}
impl Deref for CommitInner {
type Target = git2::Commit<'static>;
fn deref(&self) -> &Self::Target {
match self {
Self::Repo(repo) => repo.deref(),
Self::Owned(commit) => commit,
}
}
}
#[napi]
/// A class to represent a git commit.
pub struct Commit {
pub(crate) inner: CommitInner,
}
#[napi]
impl Commit {
#[napi]
/// Get the id (SHA1) of a repository commit
///
/// @category Commit/Methods
///
/// @signature
/// ```ts
/// class Commit {
/// id(): string;
/// }
/// ```
///
/// @returns ID(SHA1) of a repository commit.
pub fn id(&self) -> String {
self.inner.id().to_string()
}
#[napi]
/// Get the author of this commit.
///
/// @category Commit/Methods
///
/// @signature
/// ```ts
/// class Commit {
/// author(): Signature;
/// }
/// ```
///
/// @returns Author signature of this commit.
pub fn author(&self) -> crate::Result<Signature> {
let signature = Signature::try_from(self.inner.author())?;
Ok(signature)
}
#[napi]
/// Get the committer of this commit.
///
/// @category Commit/Methods
///
/// @signature
/// ```ts
/// class Commit {
/// committer(): Signature;
/// }
/// ```
///
/// @returns Committer signature of this commit.
pub fn committer(&self) -> crate::Result<Signature> {
let signature = Signature::try_from(self.inner.committer())?;
Ok(signature)
}
#[napi]
/// Get the full message of a commit.
///
/// The returned message will be slightly prettified by removing any
/// potential leading newlines.
///
/// Throws error if the message is not valid utf-8.
///
/// @category Commit/Methods
///
/// @signature
/// ```ts
/// class Commit {
/// message(): string;
/// }
/// ```
///
/// @returns Full message of this commit.
/// @throws If the message is not valid utf-8.
pub fn message(&self) -> crate::Result<String> {
let message = std::str::from_utf8(self.inner.message_raw_bytes())?.to_string();
Ok(message)
}
#[napi]
/// Get the short "summary" of the git commit message.
///
/// The returned message is the summary of the commit, comprising the first
/// paragraph of the message with whitespace trimmed and squashed.
///
/// Throws error if the summary is not valid utf-8.
///
/// @category Commit/Methods
///
/// @signature
/// ```ts
/// class Commit {
/// summary(): string | null;
/// }
/// ```
///
/// @returns Short summary of this commit message.
/// @throws If the summary is not valid utf-8.
pub fn summary(&self) -> crate::Result<Option<String>> {
let summary = match self.inner.summary_bytes() {
Some(bytes) => Some(std::str::from_utf8(bytes)?.to_string()),
None => None,
};
Ok(summary)
}
#[napi]
/// Get the long "body" of the git commit message.
///
/// The returned message is the body of the commit, comprising everything
/// but the first paragraph of the message. Leading and trailing whitespaces
/// are trimmed.
///
/// Throws error if the summary is not valid utf-8.
///
/// @category Commit/Methods
///
/// @signature
/// ```ts
/// class Commit {
/// body(): string | null;
/// }
/// ```
///
/// @returns Long body of this commit message.
/// @throws If the body is not valid utf-8.
pub fn body(&self) -> crate::Result<Option<String>> {
let body = match self.inner.body_bytes() {
Some(bytes) => Some(std::str::from_utf8(bytes)?.to_string()),
None => None,
};
Ok(body)
}
#[napi]
/// Get the commit time (i.e. committer time) of a commit.
///
/// @category Commit/Methods
///
/// @signature
/// ```ts
/// class Commit {
/// time(): Date;
/// }
/// ```
///
/// @returns Commit time of a commit.
pub fn time(&self) -> crate::Result<DateTime<Utc>> {
let time = DateTime::from_timestamp(self.inner.time().seconds(), 0).ok_or(crate::Error::InvalidTime)?;
Ok(time)
}
#[napi]
/// Get the id of the tree pointed to by this commit.
///
/// No attempts are made to fetch an object from the ODB.
///
/// @category Commit/Methods
///
/// @signature
/// ```ts
/// class Commit {
/// treeId(): string;
/// }
/// ```
///
/// @returns Get the id of the tree pointed to by a commit.
pub fn tree_id(&self) -> String {
self.inner.tree_id().to_string()
}
#[napi]
/// Get the tree pointed to by a commit.
///
/// @category Commit/Methods
///
/// @signature
/// ```ts
/// class Commit {
/// tree(): Tree;
/// }
/// ```
///
/// @returns Tree pointed to by a commit.
pub fn tree(&self, this: Reference<Commit>, env: Env) -> crate::Result<Tree> {
let tree = this.share_with(env, |commit| {
commit.inner.tree().map_err(crate::Error::from).map_err(|e| e.into())
})?;
Ok(Tree {
inner: TreeInner::Commit(tree),
})
}
#[napi]
/// Casts this Commit to be usable as an `GitObject`.
///
/// @category Commit/Methods
///
/// @signature
/// ```ts
/// class Commit {
/// asObject(): GitObject;
/// }
/// ```
///
/// @returns `GitObject` that casted from this commit.
pub fn as_object(&self) -> GitObject {
let obj = self.inner.as_object().clone();
GitObject {
inner: ObjectInner::Owned(obj),
}
}
#[napi]
/// Amend this existing commit with all non-nullable values
///
/// This creates a new commit that is exactly the same as the old commit,
/// except that any non-nullable values will be updated. The new commit has
/// the same parents as the old commit.
///
/// @category Commit/Methods
///
/// @signature
/// ```ts
/// class Commit {
/// amend(options?: AmendOptions, tree?: Tree): string;
/// }
/// ```
///
/// @param {AmendOptions} [options] - Options for amending commit.
/// @param {Tree} [tree] - Tree to use for amending commit.
/// @returns ID(SHA1) of amended commit.
pub fn amend(&self, options: Option<AmendOptions>, tree: Option<&Tree>) -> crate::Result<String> {
let opts = options.unwrap_or_default();
let update_ref = opts.update_ref;
let author = opts
.author
.and_then(|x| Signature::try_from(x).ok())
.and_then(|x| git2::Signature::try_from(x).ok());
let committer = opts
.committer
.and_then(|x| Signature::try_from(x).ok())
.and_then(|x| git2::Signature::try_from(x).ok());
let message = opts.message;
let message_encoding = opts.message_encoding;
let oid = self.inner.amend(
update_ref.as_deref(),
author.as_ref(),
committer.as_ref(),
message_encoding.as_deref(),
message.as_deref(),
tree.map(|x| x.inner.deref()),
)?;
Ok(oid.to_string())
}
}
#[napi]
impl Repository {
#[napi]
/// Lookup a reference to one of the commits in a repository.
///
/// Returns `null` if the commit does not exist.
///
/// @category Repository/Methods
///
/// @signature
/// ```ts
/// class Repository {
/// findCommit(oid: string): Commit | null;
/// }
/// ```
/// @param {string} oid - Commit ID(SHA1) to lookup.
/// @returns Commit instance found by oid. Returns `null` if the commit does not exist.
pub fn find_commit(&self, this: Reference<Repository>, env: Env, oid: String) -> Option<Commit> {
self.get_commit(this, env, oid).ok()
}
#[napi]
/// Lookup a reference to one of the commits in a repository.
///
/// @category Repository/Methods
///
/// @signature
/// ```ts
/// class Repository {
/// getCommit(oid: string): Commit;
/// }
/// ```
///
/// @param {string} oid - Commit ID(SHA1) to lookup.
/// @returns Commit instance found by oid.
/// @throws Throws error if the commit does not exist.
pub fn get_commit(&self, this: Reference<Repository>, env: Env, oid: String) -> crate::Result<Commit> {
let commit = this.share_with(env, |repo| {
repo
.inner
.find_commit_by_prefix(&oid)
.map_err(crate::Error::from)
.map_err(|e| e.into())
})?;
Ok(Commit {
inner: CommitInner::Repo(commit),
})
}
#[napi]
/// Create new commit in the repository.
///
/// If the `updateRef` is not `null`, name of the reference that will be
/// updated to point to this commit. If the reference is not direct, it will
/// be resolved to a direct reference. Use "HEAD" to update the HEAD of the
/// current branch and make it point to this commit. If the reference
/// doesn't exist yet, it will be created. If it does exist, the first
/// parent must be the tip of this branch.
///
/// @category Repository/Methods
///
/// @signature
/// ```ts
/// class Repository {
/// commit(tree: Tree, message: string, options?: CommitOptions | null | undefined): string;
/// }
/// ```
///
/// @returns ID(SHA1) of created commit.
pub fn commit(&self, tree: &Tree, message: String, options: Option<CommitOptions>) -> crate::Result<String> {
let (update_ref, author, committer, parents, signature, signature_field) = match options {
Some(opts) => {
let update_ref = opts.update_ref;
let author = opts.author.and_then(|x| Signature::try_from(x).ok());
let committer = opts.committer.and_then(|x| Signature::try_from(x).ok());
let parents = match opts.parents {
Some(parents) => {
let commits: crate::Result<Vec<git2::Commit>> = parents
.iter()
.map(|x| self.inner.find_commit_by_prefix(x).map_err(crate::Error::from))
.collect();
Some(commits?)
}
None => None,
};
let signature = opts.signature;
let signature_field = opts.signature_field;
(update_ref, author, committer, parents, signature, signature_field)
}
None => (None, None, None, None, None, None),
};
let author = author
.and_then(|x| git2::Signature::try_from(x).ok())
.or_else(|| self.inner.signature().ok())
.ok_or(crate::Error::SignatureNotFound)?;
let committer = committer
.and_then(|x| git2::Signature::try_from(x).ok())
.or_else(|| self.inner.signature().ok())
.ok_or(crate::Error::SignatureNotFound)?;
let oid = if let Some(signature_str) = signature {
let commit_content = self.inner.commit_create_buffer(
&author,
&committer,
&message,
&tree.inner,
&parents.unwrap_or_default().iter().collect::<Vec<_>>(),
)?;
let commit_content_str = std::str::from_utf8(&commit_content)?.to_string();
self
.inner
.commit_signed(&commit_content_str, &signature_str, signature_field.as_deref())?
} else {
self.inner.commit(
update_ref.as_deref(),
&author,
&committer,
&message,
&tree.inner,
&parents.unwrap_or_default().iter().collect::<Vec<_>>(),
)?
};
Ok(oid.to_string())
}
}