alpm.rs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. //
  2. // alpm.rs
  3. // Copyright (C) 2018 Paul Schaefer <schaefer.pp@gmail.com>
  4. // Distributed under terms of the LGPL-3.0+ license.
  5. //
  6. use libalpm;
  7. use libalpm::Alpm;
  8. use ini::Ini;
  9. const DEFAULT_DB_PATH: &'static str = "/var/lib/pacman/";
  10. const DEFAULT_ROOT_DIR: &'static str = "/";
  11. #[derive(Debug)]
  12. pub struct RepoPackage {
  13. pub repo: String,
  14. pub name: String,
  15. pub description: String,
  16. pub version: String,
  17. }
  18. impl RepoPackage {
  19. }
  20. pub struct Context {
  21. alpm: libalpm::Alpm,
  22. }
  23. impl Context {
  24. pub fn new() -> Result<Context, super::Error> {
  25. Self::new_from_conf("/etc/pacman.conf")
  26. }
  27. pub fn new_from_conf(conf: &str) -> Result<Context, super::Error> {
  28. let conf = Ini::load_from_file(conf).or_else(|err| Err(super::Error::ConfigError(err)))?;
  29. let options: Option<_> = conf.section(Some("options"));
  30. let rootdir = if let Some(options) = options {
  31. match options.get("RootDir") {
  32. Some(dir) => dir,
  33. None => DEFAULT_ROOT_DIR,
  34. }
  35. } else {
  36. DEFAULT_ROOT_DIR
  37. };
  38. let dbpath = if let Some(options) = options {
  39. match options.get("DBPath") {
  40. Some(dir) => dir,
  41. None => DEFAULT_DB_PATH,
  42. }
  43. } else {
  44. DEFAULT_DB_PATH
  45. };
  46. let alpm: libalpm::Alpm =
  47. Alpm::new(rootdir, dbpath).or_else(|err| Err(super::Error::AlpmError(err)))?;
  48. if let Err(e) = alpm.set_arch(&libalpm::util::uname().machine().to_owned()).or_else(|e| Err(super::Error::AlpmError(e))) {
  49. return Err(e);
  50. }
  51. Ok(Context { alpm })
  52. }
  53. pub fn search(&self, query: &str) -> Vec<RepoPackage> {
  54. self.alpm
  55. .local_db()
  56. .search(String::from(query).split(" ").collect())
  57. .unwrap_or_default()
  58. .iter()
  59. .map(|p| RepoPackage {
  60. repo: String::from(format!("{:?}", p.db(&self.alpm).name().unwrap_or_default())),
  61. name: String::from(p.name()),
  62. description: String::from(p.description()),
  63. version: String::from(format!("{}", p.version())),
  64. })
  65. .collect()
  66. }
  67. }
  68. #[cfg(test)]
  69. mod tests {
  70. use super::*;
  71. #[test]
  72. fn it_works() {
  73. }
  74. }