omr-bumper 0.2.4-alpha

An opiniated version bumper for releases. Works for us.
Documentation
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
use git2::{
	Cred,
	FetchOptions,
	PushOptions,
	RemoteCallbacks,
//	Repository,
//	Signature,
	Status,
};

//use anyhow::*;
use anyhow::bail;

use std::path::Path;


pub struct Repository {
	path: String,
	repo: Option< git2::Repository >,
}

impl Repository {
	pub fn new( path: &str ) -> Self {
		Self {
			path: path.to_owned(),
			repo: None,
		}
	}

	pub fn open( &mut self ) -> anyhow::Result<()> {
		let repo = match git2::Repository::discover( &self.path ) {
		    Ok(repo) => repo,
		    Err(e) => bail!("failed to open: {}", e),
		};

//		dbg!(&repo.state());

		self.repo = Some( repo );

		Ok(())
	}

	pub fn get_dirty( &mut self ) -> Vec<String> {
		match &self.repo {
			Some( repo ) => {
				let mut dirty = Vec::new();
				let mut check_s = Status::empty();
				check_s.insert(Status::INDEX_NEW);
				check_s.insert(Status::INDEX_MODIFIED);
				check_s.insert(Status::WT_NEW);
				check_s.insert(Status::WT_MODIFIED);

				let mut skip_s = Status::empty();
				skip_s.insert(Status::IGNORED);
				skip_s.insert(Status::WT_NEW);

				for se in repo.statuses( None ).unwrap().iter() {
					let s = se.status();
//					println!("Maybe dirty {:?} {}", s, se.path().unwrap_or( "" ) );
					if s.intersects( check_s ) {
						dirty.push( se.path().unwrap_or( "" ).to_owned());
					} else {
						if !s.intersects( skip_s ) {
							println!("Not dirty {:?} {}", s, se.path().unwrap_or( "" ) );
						}
					}
				}
				dirty
			},
			None => {
				Vec::new()
			},
		}
	}

	pub fn commit( &mut self, files: &Vec<String>, message: &str ) -> anyhow::Result<()> {
		match &self.repo {
			Some( repo ) => {
				/*
				let name = "Somebody";
				let email = "some@body.org";
				let author = Signature::now( &name, &email )?;
				let commiter = Signature::now( &name, &email )?;
				*/

				let sig = repo.signature()?;

				let mut index = match repo.index() {
					Err(e) => bail!("No index for repository {}", &e),
					Ok(index) => index,
				};
				let cwd = match std::env::current_dir() {
					Ok( wd ) => wd,
					Err( e ) => bail!("No current working directory found: {}", &e),
				};
//				dbg!(&repo.path());
//				dbg!(&repo.workdir());
				let rwd = match repo.workdir() {
					Some( wd ) => wd,
					None => bail!("No workdir for repository"),
				};
//				dbg!(&cwd);
//				dbg!(&rwd);				
				for f in files.iter() {
					let p = Path::new( &cwd ).join( &f );
//					dbg!(&p);
					// filenames are relative to working directory
					// make them relative to repository root
					let p = match p.strip_prefix( &rwd ) {
						Ok( p ) => p,
						Err( e ) => bail!("Error stripping {:?} from {:?}: {}", &rwd, &p, &e),
					};
//					dbg!(&p);
					index.add_path( &p )?;
				};

				index.write()?;

				let mut index = match repo.index() {
					Err(e) => bail!("No index for repository {}", &e),
					Ok(index) => index,
				};
/*
pub fn write_tree(&mut self) -> Result<Oid, Error>
*/
				let oid = match index.write_tree() {
					Ok( oid ) => oid,
					Err( e ) => bail!("Error writing tree for repository: {}", &e ),
				};
				index.write()?;

//				dbg!(&oid);

				let tree = match repo.find_tree(oid) {
					Ok( tree ) => tree,
					Err( e ) => bail!("Error findind tree for OID {}: {}", &oid, &e),
				};

//				dbg!(&tree);

				let parent = match repo.revparse_ext( "HEAD" ) {
					Ok( ( object, _ ) ) => object,
					Err( e ) => bail!( "Error finding HEAD {}", &e ),
				};

				let parent = match parent.as_commit() {
					Some( commit ) => commit,
					None => bail!( "Parent is not a commit" ),
				};

//				dbg!(&parent);
				/*
pub fn commit(
    &self,
    update_ref: Option<&str>,
    author: &Signature<'_>,
    committer: &Signature<'_>,
    message: &str,
    tree: &Tree<'_>,
    parents: &[&Commit<'_>]
) -> Result<Oid, Error>				
				*/
				/*
pub fn find_tree(&self, oid: Oid) -> Result<Tree<'_>, Error>				

pub fn revparse_ext(
    &self,
    spec: &str
) -> Result<(Object<'_>, Option<Reference<'_>>), Error>
				*/
				repo.commit(
					Some("HEAD"),
					&sig,
					&sig,
					message,
					&tree,
					&[ parent ],
				)?;
				Ok(())
			},
			None => bail!( "No repo open for commit" ),
		}
	}

	pub fn tag( &mut self, tag: &str, msg: &str ) -> anyhow::Result<()> {
		match &self.repo {
			Some( repo ) => {
				let rv = repo.revparse( "HEAD" )?;
				let ho = match rv.from() {
					Some( ho ) => ho,
					None => bail!( "No HEAD found!" ),
				};
				println!("Tagging {} with {}", &ho.id(), &tag);
//				dbg!(&ho);

				let sig = repo.signature()?;

				let _tag_oid = repo.tag( tag, &ho, &sig, msg, true )?;
//				dbg!(&tag_oid);
				Ok(())
/*
pub fn tag(
    &self,
    name: &str,
    target: &Object<'_>,
    tagger: &Signature<'_>,
    message: &str,
    force: bool
) -> Result<Oid, Error>
*/
			},
			None => bail!( "No repo open for tag" ),
		}
	}

	fn credentials_cb( _url: &str, username_from_url: Option<&str>, _allowed_types: git2::CredentialType ) -> Result<Cred, git2::Error> {
//		dbg!(&username_from_url);
		Cred::ssh_key(
			username_from_url.unwrap(),
			None,
			std::path::Path::new(&format!("{}/.ssh/id_ed25519", std::env::var("HOME").unwrap())),
//			std::path::Path::new(&format!("{}/.ssh/id_rsa", std::env::var("HOME").unwrap())),
			None,
		)
	}

	pub fn fetch( &mut self ) -> anyhow::Result<usize> {
		match &self.repo {
			Some( repo )	=> {
				let remote_name = "origin";
				let mut remote = match repo.find_remote( &remote_name ) {
					Ok( remote )	=> remote,
					Err( e )		=> bail!( "Couldn't find remote({}): {}", &remote_name, &e ),
				};

//				dbg!(&remote.name(), &remote.url());

				let mut cbs = RemoteCallbacks::new();
				cbs.credentials(|url, username_from_url, allowed_types| { Repository::credentials_cb( url, username_from_url, allowed_types ) });
				cbs.transfer_progress(|progress| {
					println!("Transfer progress: {}", progress.received_bytes());
					println!("{}/{} objects", progress.received_objects(), progress.total_objects());
//					dbg!(&progress.received_bytes());
					true
				});
				let mut opts = FetchOptions::new();
				opts.remote_callbacks( cbs );
				remote.fetch(&["main"], Some( &mut opts ), None)?;
				let stats = remote.stats();
				println!("Fetched {} bytes.", stats.received_bytes());
				println!("Fetched {} objects.", stats.received_objects());
				Ok(stats.total_objects())
			},
			None			=> bail!( "No repo open for fetch" ),
		}
	}

	pub fn rebase( &mut self ) -> anyhow::Result<()> {
		match &self.repo {
			Some( repo ) => {
//				let head = repo.head()?; // wrong, this is local HEAD, we want origin/HEAD
//				let upstream = repo.reference_to_annotated_commit( &head )?;
				let rv = repo.revparse( "origin/HEAD" )?;
				let oho = match rv.from() {
					Some( oho ) => oho,
					None => bail!( "No origin/HEAD found!" ),
				};
//				dbg!(&oho);

				let upstream = match repo.find_annotated_commit( oho.id() ) {
					Ok( commit ) => commit,
					Err( e ) => bail!( "No commit for origin/HEAD! {}", &e ),
				};
/*		
pub fn revparse(&self, spec: &str) -> Result<Revspec<'_>, Error>
*/				
				println!("Rebasing on upstream {} {}", upstream.id(), "" ); //upstream.refname().unwrap_or("") );
//				let upstream = None; // AnnotatedCommit
				let mut rebase = repo.rebase( None, Some( &upstream ), None, None )?;
				println!("{}", rebase.len());
				while let Some( ro ) = rebase.next() {

//				};
//				for ro in &mut rebase {
					match ro {
						Ok( _ro ) => {
//							dbg!( &ro );
							// commit
							/*
pub fn commit(
    &mut self,
    author: Option<&Signature<'_>>,
    committer: &Signature<'_>,
    message: Option<&str>
) -> Result<Oid, Error>
*/							
							let sig = repo.signature()?;

							match rebase.commit(
								None,
								&sig,
								None,
							) {
								Ok( _r ) => {
//									dbg!( &r );
								},
								Err( e ) => {
									dbg!( &e );
									// :TODO: decide when to bail
//									bail!( "Rebase Error {:?}", &e );
								},
							}
						},
						Err( e ) => {
							dbg!( &e );
						},
					}
				}
//				rebase.abort()?;
				rebase.finish(None)?;
//				dbg!(&rebase);

			},
			None => bail!( "No repo open for rebase" ),
		}
		Ok(())
		/*

pub fn head(&self) -> Result<Reference<'_>, Error>

pub fn reference_to_annotated_commit(
    &self,
    reference: &Reference<'_>
) -> Result<AnnotatedCommit<'_>, Error>


pub fn rebase(
    &self,
    branch: Option<&AnnotatedCommit<'_>>,
    upstream: Option<&AnnotatedCommit<'_>>,
    onto: Option<&AnnotatedCommit<'_>>,
    opts: Option<&mut RebaseOptions<'_>>
) -> Result<Rebase<'_>, Error>
		*/
	}

	pub fn push( &mut self ) -> anyhow::Result<usize> {
		match &self.repo {
			Some( repo ) => {
				let remote_name = "origin";
				let mut remote = match repo.find_remote( &remote_name ) {
					Ok( remote )	=> remote,
					Err( e )		=> bail!( "Couldn't find remote({}): {}", &remote_name, &e ),
				};

				let mut cbs = RemoteCallbacks::new();
				cbs.credentials(|url, username_from_url, allowed_types| { Repository::credentials_cb( url, username_from_url, allowed_types ) });
				cbs.transfer_progress(|progress| {
					println!("Transfer progress: {}", progress.received_bytes());
					println!("{}/{} objects", progress.received_objects(), progress.total_objects());
//					dbg!(&progress.received_bytes());
					true
				});
				let mut opts = PushOptions::new();
				opts.remote_callbacks( cbs );
				remote.push(
					&["refs/heads/main"],
					Some( &mut opts )
				)?;

				/*
				// only works for fetch!!!
				let stats = remote.stats();
				println!("Pushed {} bytes.", stats.received_bytes());
				println!("Pushed {} objects.", stats.received_objects());
				Ok(stats.total_objects())
				*/

				Ok( 0 )

				/*
pub fn push<Str: AsRef<str> + IntoCString + Clone>(
    &mut self,
    refspecs: &[Str],
    opts: Option<&mut PushOptions<'_>>
) -> Result<(), Error>
				*/
			},
			None => bail!( "No repo open for push" ),
		}
	}

	pub fn push_tag( &mut self, tag: &str ) -> anyhow::Result<usize> {
		match &self.repo {
			Some( repo ) => {
				let remote_name = "origin";
				let mut remote = match repo.find_remote( &remote_name ) {
					Ok( remote )	=> remote,
					Err( e )		=> bail!( "Couldn't find remote({}): {}", &remote_name, &e ),
				};

				let mut cbs = RemoteCallbacks::new();
				cbs.credentials(|_url, username_from_url, _allowed_types| {
//					dbg!(&username_from_url);
					Cred::ssh_key(
						username_from_url.unwrap(),
						None,
						std::path::Path::new(&format!("{}/.ssh/id_ed25519", std::env::var("HOME").unwrap())),
//						std::path::Path::new(&format!("{}/.ssh/id_rsa", std::env::var("HOME").unwrap())),
						None,
					)
				});
				cbs.transfer_progress(|progress| {
					println!("Transfer progress: {}", progress.received_bytes());
					println!("{}/{} objects", progress.received_objects(), progress.total_objects());
//					dbg!(&progress.received_bytes());
					true
				});
				cbs.push_update_reference(|name, status|{
					println!("Push Update Reference: {} -> {:?}", name, status);
					Ok(())
				});
				let mut opts = PushOptions::new();
				opts.remote_callbacks( cbs );
				let tag_ref = format!("refs/tags/{}", &tag);
				println!("Pushing ref {}", &tag_ref);
				remote.push(
					&[ &tag_ref ],
					Some( &mut opts )
				)?;
//git push <corresponding remote> refs/tags/*:refs/tags/*	

				/*
				// only works for fetch!!!
				let stats = remote.stats();
				println!("Pushed {} bytes.", stats.received_bytes());
				println!("Pushed {} objects.", stats.received_objects());
				Ok(stats.total_objects())
				*/

				Ok( 0 )

				/*
pub fn push<Str: AsRef<str> + IntoCString + Clone>(
    &mut self,
    refspecs: &[Str],
    opts: Option<&mut PushOptions<'_>>
) -> Result<(), Error>
				*/
			},
			None => bail!( "No repo open for push" ),
		}
	}

}