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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
//! A library to access the functionality of libalpm (the library used by pacman).
//!
//! # Getting started
//! The main struct here is `Alpm`. It is responsible for wrapping an alpm database and filesystem,
//! and providing functionality for thtat alpm instance. For example...
//!
//! ```ignore
//! use libalpm::Alpm;
//! use libalpm::util;
//!
//! // get the architecture (e.g. x86_64).
//! let arch = util::uname().machine().to_owned();
//!
//! let alpm = Alpm::new("/", "/var/lib/pacman"); // default locations on arch linux
//! alpm
//! ```

#![feature(untagged_unions)]
#![feature(pub_restricted)]

extern crate alpm_sys;
extern crate url;
extern crate libc;
extern crate printf;
extern crate chrono;
#[macro_use] extern crate lazy_static;

mod error;
mod event;
mod package;
mod db;
mod pgp;
mod log;
mod callbacks;
mod options;
mod types;
pub mod util;

use std::ffi::{CString, CStr};
use std::ops::Drop;
use std::path::{PathBuf};
use std::sync::Mutex;
use std::borrow::Borrow;
use std::mem;

use alpm_sys::*;
use libc::{c_char, c_void};

pub use options::{Options, RepoOptions};
pub use error::{Error, AlpmResult};
pub use log::{LogLevel, LogLevels};
pub use event::Event;
pub use package::{Package, PackageRef, Group, PackageVersion, PackageFrom, Reason, Validation,
    ValidationMethod, Dependency, FileList, File, Backup, VersionConstraintType};
pub use db::Db;
pub use pgp::SigLevel;
pub use types::{Caps, DownloadResult};
use callbacks::{alpm_cb_log, alpm_cb_download, alpm_cb_totaldl, alpm_cb_fetch, alpm_cb_event};

// callbacks
lazy_static! {
    static ref LOG_CB: Mutex<Option<Box<FnMut(LogLevels, String) + Send>>> = Default::default();
    static ref DOWNLOAD_CB: Mutex<Option<Box<FnMut(&str, u64, u64) + Send>>> = Default::default();
    static ref FETCH_CB: Mutex<Option<Box<FnMut(&str, &str, bool) -> DownloadResult + Send>>> = Default::default();
    static ref DLTOTAL_CB: Mutex<Option<Box<FnMut(u64) + Send>>> = Default::default();
    static ref EVENT_CB: Mutex<Option<Box<FnMut(Event) + Send>>> = Default::default();
    //static ref QUESTION_CB: Mutex<Option<Box<FnMut(LogLevels, String) + Send>>> = Default::default();
    //static ref PROGRESS_CB: Mutex<Option<Box<FnMut(LogLevels, String) + Send>>> = Default::default();
}

/// A handle on an alpm instance
///
/// Note that I have NOT checked whether the interface is threadsafe, so it's best to use only one
/// instance of Alpm at present (doing your own synchronization if you want to share between
/// threads). Also, callbacks must be stored in global state, so if they are changed for one they
/// will be changed for all.
#[derive(Debug)]
pub struct Alpm {
    handle: *const Struct_alpm_handle,
}

impl Alpm {
    /// Get a handle on the alpm instance defined by the given root/db_path
    pub fn new(root: &str, db_path: &str) -> AlpmResult<Alpm> {
        // Requires alloc, but str is more standard
        let root = CString::new(root)?;
        let db_path = CString::new(db_path)?;
        unsafe {
            let mut err: alpm_errno_t = 0;
            let handle = alpm_initialize(root.as_ptr(), db_path.as_ptr(), &mut err);
            if err != 0 {
                Err(Error::from(err))
            } else {
                let alpm = Alpm {
                    handle: handle
                };
                Ok(alpm)
            }
        }
    }

    /// Creates an alpm instance with the given options.
    ///
    /// TODO will only be implemented after the rest of the library is finished.
    pub fn with_options(options: &Options) -> AlpmResult<Alpm> {
        unimplemented!()
    }

    /// Gets the current (last) error status. Most functions use this internally to get the
    /// error type to return, so there isn't much need to use this externally.
    pub fn error(&self) -> Option<Error> {
        let code = unsafe { alpm_errno(self.handle) };
        if code == 0 {
            None
        } else {
            Some(code.into())
        }
    }

    /// Logs a message using alpm's built in logging functionality.
    ///
    /// TODO test if all prefixes are allowed, or just DEBUG etc., & test generally
    pub fn log_action<T, U>(&self, prefix: &str, msg: &str) -> AlpmResult<()> {
        let prefix = CString::new(prefix)?;
        let msg = CString::new(msg.replace("%", "%%"))?;
        let res = unsafe {alpm_logaction(self.handle, prefix.as_ptr(), msg.as_ptr()) };
        if res == 0 {
            Ok(())
        } else {
            Err(self.error().unwrap_or(Error::__Unknown))
        }
    }

    /// Fetch a remote pkg from the given URL and return its path.
    pub fn fetch_pkgurl(&self, url: &str) -> AlpmResult<PathBuf> {
        unsafe {
            let url = CString::new(url)?;
            let path = alpm_fetch_pkgurl(self.handle, url.as_ptr());
            if path.is_null() {
                Err(Error::__Unknown)
            } else {
                // copy path into rust alloc'd data struct
                let path_rust = PathBuf::from(CStr::from_ptr(path).to_str()?);
                libc::free(path as *mut c_void);
                Ok(path_rust)
            }
        }
    }

    /// Set the callback called when a log message is received.
    pub fn log_function<F>(&self, func: F)
        where F: FnMut(LogLevels, String) + Send + 'static
    {
        let mut cb = LOG_CB.lock().unwrap();
        (*cb) = Some(Box::new(func));
        unsafe { alpm_option_set_logcb(self.handle, Some(alpm_cb_log)); }
    }

    /// Clears the log callback.
    pub fn clear_log_function(&self) {
        let mut cb = LOG_CB.lock().unwrap();
        (*cb) = None;
        unsafe { alpm_option_set_logcb(self.handle, None); }
    }

    /// Set the callback called to report progress on downloading a file.
    pub fn file_download_progress_function<F>(&self, func: F)
        where F: FnMut(&str, u64, u64) + Send + 'static
    {
        let mut cb = DOWNLOAD_CB.lock().unwrap();
        (*cb) = Some(Box::new(func));
        unsafe { alpm_option_set_dlcb(self.handle, Some(alpm_cb_download)); }
    }

    /// Clears the file download progress callback.
    pub fn clear_file_download_progress_function(&self) {
        let mut cb = DOWNLOAD_CB.lock().unwrap();
        (*cb) = None;
        unsafe { alpm_option_set_dlcb(self.handle, None); }
    }

    /// Set the callback called to report progress on total download
    pub fn total_download_progress_function<F>(&self, func: F)
        where F: FnMut(u64) + Send + 'static
    {
        let mut cb = DLTOTAL_CB.lock().unwrap();
        (*cb) = Some(Box::new(func));
        unsafe { alpm_option_set_totaldlcb(self.handle, Some(alpm_cb_totaldl)); }
    }

    /// Clears the total download progress callback.
    pub fn clear_total_download_progress_function(&self) {
        let mut cb = DLTOTAL_CB.lock().unwrap();
        (*cb) = None;
        unsafe { alpm_option_set_totaldlcb(self.handle, None); }
    }

    /// Set the callback called to download a file.
    ///
    /// Providing this function is optional and it is recommended that you don't set it (and use
    /// the built-in fetch fn). This could be useful e.g. if you are behind a complicated proxy or
    /// want to use something other than http to fetch.
    ///
    /// # Safety
    /// Note that if you supply this function, you promise that if you return DownloadResult::Ok,
    /// the requested file is correctly located in the given location.
    ///
    /// A panic in the function will cause DownloadResult::Err to be sent to the underlying
    /// libalpm (i.e. not undefined behaviour).
    ///
    /// TODO investigate whether safe to relax 'static bound
    pub unsafe fn fetch_function<F>(&self, func: F)
        where F: FnMut(&str, &str, bool) -> DownloadResult + Send + 'static
    {
        let mut cb = FETCH_CB.lock().unwrap();
        (*cb) = Some(Box::new(func));
        alpm_option_set_fetchcb(self.handle, Some(alpm_cb_fetch));
    }

    /// Clears the file download callback, falling back to built-in fetch functionality.
    pub fn clear_fetch_function(&self) {
        let mut cb = DLTOTAL_CB.lock().unwrap();
        (*cb) = None;
        unsafe { alpm_option_set_fetchcb(self.handle, None); }
    }

    /// Sets the function called when an event occurs
    pub fn event_function<F>(&self, func: F)
        where F: FnMut(Event) + Send + 'static
    {
        let mut cb = EVENT_CB.lock().unwrap();
        (*cb) = Some(Box::new(func));
        unsafe { alpm_option_set_eventcb(self.handle, Some(alpm_cb_event)); }
    }

    /// Clears the file download callback, falling back to built-in fetch functionality.
    pub fn clear_event_function(&self) {
        let mut cb = DLTOTAL_CB.lock().unwrap();
        (*cb) = None;
        unsafe { alpm_option_set_eventcb(self.handle, None); }
    }

    /// Sets the function called when a question needs answering (todo i think)
    pub fn question_function<F>(&self, func: F)
        where F: FnMut() + Send + 'static
    {
        unimplemented!()
    }

    /// Clears the function called when a question needs answering (todo i think)
    pub fn clear_question_function(&self) {
        unimplemented!()
    }

    /// Sets the function called to show operation progress
    pub fn progress_function<F>(&self, func: F)
        where F: FnMut() + Send + 'static
    {
        unimplemented!()
    }

    /// Clears the function called to show operation progress
    pub fn clear_progress_function(&self) {
        unimplemented!()
    }

    /// Get the root path used in this instance of alpm
    ///
    /// The api doesn't make clear the lifetime of the result, so I am conservative (same goes for
    /// db_path)
    pub fn root<'a>(&'a self) -> &'a str {
        let root = unsafe { CStr::from_ptr(alpm_option_get_root(self.handle)) };
        root.to_str().ok().expect("instance root path is not utf8")
    }

    /// Get the database path used in this instance of alpm
    pub fn db_path<'a>(&'a self) -> &'a str {
        let db_path = unsafe { CStr::from_ptr(alpm_option_get_dbpath(self.handle)) };
        db_path.to_str().ok().expect("instance db path is not utf8")
    }

    /// Get the lockfile path used in this instance of alpm
    pub fn lockfile<'a>(&'a self) -> &'a str {
        let lockfile = unsafe { CStr::from_ptr(alpm_option_get_lockfile(self.handle)) };
        lockfile.to_str().ok().expect("instance lockfile path is not utf8")
    }

    /// Gets a list of the cache directories in use by this instance of alpm
    pub fn cache_dirs(&self) -> Vec<&str> {
        unsafe {
            let cachedirs = alpm_option_get_cachedirs(self.handle);
            util::alpm_list_to_vec(cachedirs, |char_ptr| {
                CStr::from_ptr(char_ptr as *const c_char).to_str().unwrap()
            })
        }
    }

    /// Sets a list of the cache directories in use by this instance of alpm
    pub fn set_cache_dirs(&self) {
        unimplemented!()
    }

    /// Adds a cache directory for use by this instance of alpm
    pub fn add_cache_dir(&self) {
        unimplemented!()
    }

    /// Removes a cache directory in use by this instance of alpm
    pub fn remove_cache_dir(&self) {
        unimplemented!()
    }

    /// Gets a list of the hook directories in use by this instance of alpm
    pub fn hook_dirs(&self) {
        unimplemented!()
    }

    /// Sets a list of the hook directories in use by this instance of alpm
    pub fn set_hook_dirs(&self) {
        unimplemented!()
    }

    /// Adds a hook directory for use by this instance of alpm
    pub fn add_hook_dir(&self) {
        unimplemented!()
    }

    /// Removes a hook directory in use by this instance of alpm
    pub fn remove_hook_dir(&self) {
        unimplemented!()
    }

    /// Gets the log file location used by this instance of alpm.
    pub fn log_file(&self) {
        unimplemented!()
    }

    /// Sets the log file location used by this instance of alpm.
    pub fn set_log_file(&self) {
        unimplemented!()
    }

    /// Gets the path to alpm's GnuPG home directory
    pub fn gpg_dir(&self) {
        unimplemented!()
    }

    /// Sets the path to alpm's GnuPG home directory
    pub fn set_gpg_dir(&self) {
        unimplemented!()
    }

    /// Gets whether this instance of alpm should log events to syslog
    pub fn use_syslog(&self) {
        unimplemented!()
    }

    /// Sets whether this instance of alpm should log events to syslog
    pub fn set_use_syslog(&self) {
        unimplemented!()
    }

    /// Gets a list of the packages that should not be upgraded.
    pub fn no_upgrades(&self) {
        unimplemented!()
    }

    /// Sets a list of the packages that should not be upgraded.
    pub fn set_no_upgrades(&self) {
        unimplemented!()
    }

    /// Adds a package to the list that should not be upgraded.
    pub fn add_no_upgrade(&self) {
        unimplemented!()
    }

    /// Removes a package from the list that should not be upgraded.
    pub fn remove_no_upgrade(&self) {
        unimplemented!()
    }

    /// Gets a list of the packages that should be ignored.
    pub fn ignore_pkgs(&self) {
        unimplemented!()
    }

    /// Sets a list of the packages that should be ignored.
    pub fn set_ignore_pkgs(&self) {
        unimplemented!()
    }

    /// Adds a package to the list that should be ignored.
    pub fn add_ignore_pkg(&self) {
        unimplemented!()
    }

    /// Removes a package from the list that should be ignored.
    pub fn remove_ignore_pkg(&self) {
        unimplemented!()
    }

    /// Gets a list of the groups that should be ignored.
    pub fn ignore_groups(&self) {
        unimplemented!()
    }

    /// Sets a list of the groups that should be ignored.
    pub fn set_ignore_groups(&self) {
        unimplemented!()
    }

    /// Adds a group to the list that should be ignored.
    pub fn add_ignore_group(&self) {
        unimplemented!()
    }

    /// Removes a group from the list that should be ignored.
    pub fn remove_ignore_group(&self) {
        unimplemented!()
    }

    /// Gets a list of the dependencies that should be ignored by a sys-upgrade.
    pub fn assume_installed(&self) {
        unimplemented!()
    }

    /// Sets a list of the dependencies that should be ignored by a sys-upgrade.
    pub fn set_assume_installed(&self) {
        unimplemented!()
    }

    /// Adds a package to the list of dependencies that should be ignored by a sys-upgrade.
    pub fn add_assume_installed(&self) {
        unimplemented!()
    }

    /// Removes a package from the list of dependencies that should be ignored by a sys-upgrade.
    pub fn remove_assume_installed(&self) {
        unimplemented!()
    }

    /// Gets the targeted architecture.
    pub fn arch(&self) -> Option<&str> {
        unsafe {
            let arch = alpm_option_get_arch(self.handle);
            if arch.is_null() {
                None
            } else {
                Some(CStr::from_ptr(arch).to_str().ok()
                    .expect("targeted arch is not utf8"))
            }
        }
    }

    /// Sets the targeted architecture.
    pub fn set_arch(&self, arch: &str) -> AlpmResult<()> {
        let arch = CString::new(arch)?;
        let res = unsafe { alpm_option_set_arch(self.handle, arch.as_ptr()) };
        if res == 0 {
            Ok(())
        } else {
            Err(self.error().unwrap_or(Error::__Unknown))
        }
    }

    /// Gets the delta ratio
    pub fn delta_ratio(&self) -> f64 {
        unsafe { alpm_option_get_deltaratio(self.handle) }
    }

    /// Sets the targeted architecture
    pub fn set_delta_ratio(&self, r: f64) -> AlpmResult<()> {
        let res = unsafe { alpm_option_set_deltaratio(self.handle, r) };
        if res == 0 {
            Ok(())
        } else {
            Err(self.error().unwrap_or(Error::__Unknown))
        }
    }

    /// Gets whether alpm will check disk space before operations
    pub fn check_space(&self) -> bool {
        unsafe { alpm_option_get_checkspace(self.handle) != 0 }
    }

    /// Sets the targeted architecture
    pub fn set_check_space(&self, check: bool) -> AlpmResult<()> {
        let res = unsafe { alpm_option_set_checkspace(self.handle, if check { 1 } else { 0 }) };
        if res == 0 {
            Ok(())
        } else {
            Err(self.error().unwrap_or(Error::__Unknown))
        }
    }

    /// Gets the registered database extension used on the filesystem
    pub fn db_extension(&self) -> &str {
        unsafe {
            let ext = alpm_option_get_dbext(self.handle);
            assert!(!ext.is_null(), "Database extension should never be null");
            CStr::from_ptr(ext).to_str().ok().expect("Database extensions not valid utf8")
        }
    }

    /// Sets the targeted architecture
    pub fn set_db_extension(&self, ext: &str) -> AlpmResult<()> {
        let cstr = CString::new(ext)?;
        let res = unsafe { alpm_option_set_dbext(self.handle, cstr.as_ptr()) };
        if res == 0 {
            Ok(())
        } else {
            Err(self.error().unwrap_or(Error::__Unknown))
        }
    }

    /// Gets the default signing level
    pub fn default_sign_level(&self) -> SigLevel {
        unsafe { alpm_option_get_default_siglevel(self.handle).into() }
    }

    /// Sets the default signing level
    pub fn set_default_sign_level(&self, s: SigLevel) -> AlpmResult<()> {
        let res = unsafe { alpm_option_set_default_siglevel(self.handle, s.into()) };
        if res == 0 {
            Ok(())
        } else {
            Err(self.error().unwrap_or(Error::__Unknown))
        }
    }

    /// Gets the default signing level
    pub fn local_file_sign_level(&self) -> SigLevel {
        unsafe { alpm_option_get_local_file_siglevel(self.handle).into() }
    }

    /// Sets the default signing level
    pub fn set_local_file_sign_level(&self, s: SigLevel) -> AlpmResult<()> {
        let res = unsafe { alpm_option_set_local_file_siglevel(self.handle, s.into()) };
        if res == 0 {
            Ok(())
        } else {
            Err(self.error().unwrap_or(Error::__Unknown))
        }
    }

    /// Gets the default signing level
    pub fn remote_file_sign_level(&self) -> SigLevel {
        unsafe { alpm_option_get_remote_file_siglevel(self.handle).into() }
    }

    /// Sets the default signing level
    pub fn set_remote_file_sign_level(&self, s: SigLevel) -> AlpmResult<()> {
        let res = unsafe { alpm_option_set_remote_file_siglevel(self.handle, s.into()) };
        if res == 0 {
            Ok(())
        } else {
            Err(self.error().unwrap_or(Error::__Unknown))
        }
    }

    /// Get the local database instance.
    pub fn local_db<'a>(&'a self) -> Db<'a> {
        unsafe { Db::new(alpm_get_localdb(self.handle), self) }
    }

    /// Get a list of remote databases registered.
    pub fn sync_dbs<'a>(&'a self) -> Vec<Db<'a>> {
        //use std::error::Error;
        unsafe {
            let raw_list = alpm_get_syncdbs(self.handle);
            //println!("{:?}", raw_list);
            //println!("error: {:?}", self.error().unwrap().description());
            util::alpm_list_to_vec(raw_list, |ptr| {
                Db::new(ptr as *const Struct_alpm_db, &self)
            })
        }
    }

    /// Register a sync db (remote db). You will need to attach servers to the db to be able to
    /// sync
    pub fn register_sync_db<'a>(&'a self, treename: &str, level: SigLevel) -> AlpmResult<Db<'a>> {
        unsafe {
            let db = alpm_register_syncdb(self.handle,
                                          (CString::new(treename)?).as_ptr(),
                                          level.into());
            if db.is_null() {
                Err(self.error().unwrap_or(Error::__Unknown))
            } else {
                Ok(Db::new(db, &self))
            }
        }
    }

    /*
    /// Unregister all sync dbs.
    ///
    /// # Safety
    /// There must not be any remaining Db instances, as these will be de-allocated.
    pub unsafe fn unregister_all_sync_dbs(&self) -> AlpmResult<()> {
        let res = alpm_unregister_all_syncdbs(self.handle);
        if res == 0 {
            Ok(())
        } else {
            Err(self.error().unwrap_or(Error::__Unknown))
        }
    }
    */

    /// Start a package modification transaction
    pub fn init_transaction(self, flags: TransactionFlags) -> Result<Transaction, (Error, Alpm)> {
        let res = unsafe { alpm_trans_init(self.handle, flags.into()) };
        if res == 0 {
            Ok(Transaction(self))
        } else {
            Err((self.error().unwrap_or(Error::__Unknown), self))
        }
    }
}

impl Drop for Alpm {
    fn drop(&mut self) {
        unsafe { alpm_release(self.handle); }
    }
}

/// A transaction of package operations
///
/// Consumes an Alpm instance as only 1 transaction can be performed at a time. Use `commit` or
/// `rollback` to recover the Alpm instance.
pub struct Transaction(Alpm);

impl Transaction {

    /// Returns the flags for the current transaction.
    pub fn flags(&self) -> TransactionFlags {
        unsafe { alpm_trans_get_flags(self.0.handle).into() }
    }

    /// Gets packages added by the current transaction.
    pub fn added_packages<'a>(&'a self) -> Vec<&'a PackageRef> {
        unimplemented!()
    }

    /// Gets packages removed by the current transaction.
    pub fn removed_packages<'a>(&'a self) -> Vec<&'a PackageRef> {
        unimplemented!()
    }

    /// Prepares a transaction for committing.
    pub fn prepare<'a>(&'a self) -> AlpmResult<()> {
        use std::ptr;
        unsafe {
            let mut p: *mut alpm_list_t = ptr::null_mut();
            let res = alpm_trans_prepare(self.0.handle, &mut p as *mut _);
            if res == 0 {
                Ok(())
            } else {
                Err(self.0.error().unwrap_or(Error::__Unknown))
            }
        }
    }

    /// Commits the transaction and returns the alpm instance. TODO conflict type
    pub fn commit(self) -> Result<Alpm, (Error, Vec<()>, Transaction)> {
        use std::ptr;
        unsafe {
            let mut p: *mut alpm_list_t = ptr::null_mut();
            let res = alpm_trans_commit(self.0.handle, &mut p as *mut _);
            if res == 0 {
                Ok(self.0)
            } else {
                Err((self.0.error().unwrap_or(Error::__Unknown), Vec::new(), self))
            }
        }
    }

    /// Releases (discards) the transaction and returns the alpm instance.
    pub fn release(self) -> Result<Alpm, (Error, Alpm)> {
        unimplemented!()
    }

    /// Adds a system upgrade to this transaction.
    pub fn sys_upgrade(&self, enable_downgrade: bool) -> AlpmResult<()> {
        unsafe {
            let res = alpm_sync_sysupgrade(self.0.handle, enable_downgrade as libc::c_int);
            if res == 0 {
                Ok(())
            } else {
                Err(self.0.error().unwrap_or(Error::__Unknown))
            }
        }
    }

    /// Adds a new package to system in this transaction.
    pub fn add_package(&self, pkg: &PackageRef) -> AlpmResult<()> {
        unimplemented!()
    }

    /// Removes a package from the system in this transaction.
    pub fn remove_package(&self, pkg: &PackageRef) -> AlpmResult<()> {
        unimplemented!()
    }
}

/// Get the version of the attached libalpm
pub fn version() -> &'static str {
    unsafe {
        let v = CStr::from_ptr(alpm_version());
        v.to_str().ok().expect("For some reason the libalpm version is not utf8")
    }
}

/// Get the capabilities of the attached libalpm
pub fn capabilities() -> Caps {
    unsafe { alpm_capabilities().into() }
}

#[derive(Default, Debug, PartialEq, Eq, Copy, Clone)]
pub struct TransactionFlags {
    /// Ignore dependency checks
    no_deps: bool,
    /// Ignore file conflicts and overwrite files
    force: bool,
    /// Delete files even if they are tagged as backup
    no_save: bool,
    /// Ignore version numbers when checking dependencies
    no_dep_version: bool,
    /// Remove also any packages depending on a package being removed
    cascade: bool,
    /// Remove packages and their unneeded deps (not explicitally installed)
    recurse: bool,
    /// Modify database but do not commit changes to filesystem
    db_only: bool,
    /// Mark all installed packages as dependencies.
    all_deps: bool,
    /// Only download packages and do not actually install.
    download_only: bool,
    /// Do not execute install scriptlets after installing
    no_scriptlet: bool,
    /// Ignore dependency conflicts
    no_conflicts: bool,
    /// Do not install a package if it is already installed and up to date
    needed: bool,
    /// Mark all installed packages as explicitally requested.
    all_explicit: bool,
    /// Do not remove a package if it is needed by another one.
    unneeded: bool,
    /// Remove also explicitly installed unneeded deps (use with `recurse: true`)
    recurse_all: bool,
    /// Do not lock the database during the operation.
    no_lock: bool,
}

impl Into<u32> for TransactionFlags {
    fn into(self) -> u32 {
        let mut acc = 0;
        if self.no_deps {
            acc |= ALPM_TRANS_FLAG_NODEPS;
        }
        if self.force {
            acc |= ALPM_TRANS_FLAG_FORCE;
        }
        if self.no_save {
            acc |= ALPM_TRANS_FLAG_NOSAVE;
        }
        if self.no_dep_version {
            acc |= ALPM_TRANS_FLAG_NODEPVERSION;
        }
        if self.cascade {
            acc |= ALPM_TRANS_FLAG_CASCADE;
        }
        if self.recurse {
            acc |= ALPM_TRANS_FLAG_RECURSE;
        }
        if self.db_only {
            acc |= ALPM_TRANS_FLAG_DBONLY;
        }
        if self.all_deps {
            acc |= ALPM_TRANS_FLAG_ALLDEPS;
        }
        if self.download_only {
            acc |= ALPM_TRANS_FLAG_DOWNLOADONLY;
        }
        if self.no_scriptlet {
            acc |= ALPM_TRANS_FLAG_NOSCRIPTLET;
        }
        if self.no_conflicts {
            acc |= ALPM_TRANS_FLAG_NOCONFLICTS;
        }
        if self.needed {
            acc |= ALPM_TRANS_FLAG_NEEDED;
        }
        if self.all_explicit {
            acc |= ALPM_TRANS_FLAG_ALLEXPLICIT;
        }
        if self.unneeded {
            acc |= ALPM_TRANS_FLAG_UNNEEDED;
        }
        if self.recurse_all {
            acc |= ALPM_TRANS_FLAG_RECURSEALL;
        }
        if self.no_lock {
            acc |= ALPM_TRANS_FLAG_NOLOCK;
        }
        acc
    }
}

impl From<u32> for TransactionFlags {
    fn from(from: u32) -> TransactionFlags {
        TransactionFlags {
            no_deps: from & ALPM_TRANS_FLAG_NODEPS != 0,
            force: from & ALPM_TRANS_FLAG_FORCE != 0,
            no_save: from & ALPM_TRANS_FLAG_NOSAVE != 0,
            no_dep_version: from & ALPM_TRANS_FLAG_NODEPVERSION != 0,
            cascade: from & ALPM_TRANS_FLAG_CASCADE != 0,
            recurse: from & ALPM_TRANS_FLAG_RECURSE != 0,
            db_only: from & ALPM_TRANS_FLAG_DBONLY != 0,
            all_deps: from & ALPM_TRANS_FLAG_ALLDEPS != 0,
            download_only: from & ALPM_TRANS_FLAG_DOWNLOADONLY != 0,
            no_scriptlet: from & ALPM_TRANS_FLAG_NOSCRIPTLET != 0,
            no_conflicts: from & ALPM_TRANS_FLAG_NOCONFLICTS != 0,
            needed: from & ALPM_TRANS_FLAG_NEEDED != 0,
            all_explicit: from & ALPM_TRANS_FLAG_ALLEXPLICIT != 0,
            unneeded: from & ALPM_TRANS_FLAG_UNNEEDED != 0,
            recurse_all: from & ALPM_TRANS_FLAG_RECURSEALL != 0,
            no_lock: from & ALPM_TRANS_FLAG_NOLOCK != 0,
        }
    }
}

#[test]
fn test_transaction_flags() {
    let t: TransactionFlags = Default::default();
    // (my) sanity check that deriving bool = false
    assert!(!t.no_lock);
}