copy.cc 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: copy.cc,v 1.7.2.1 2004/01/16 18:58:50 mdz Exp $
  4. /* ######################################################################
  5. Copy URI - This method takes a uri like a file: uri and copies it
  6. to the destination file.
  7. ##################################################################### */
  8. /*}}}*/
  9. // Include Files /*{{{*/
  10. #include <config.h>
  11. #include <apt-pkg/fileutl.h>
  12. #include <apt-pkg/strutl.h>
  13. #include <apt-pkg/acquire-method.h>
  14. #include <apt-pkg/error.h>
  15. #include <apt-pkg/hashes.h>
  16. #include <string>
  17. #include <sys/stat.h>
  18. #include <sys/time.h>
  19. #include <apti18n.h>
  20. /*}}}*/
  21. class CopyMethod : public pkgAcqMethod
  22. {
  23. virtual bool Fetch(FetchItem *Itm);
  24. public:
  25. CopyMethod() : pkgAcqMethod("1.0",SingleInstance) {};
  26. };
  27. // CopyMethod::Fetch - Fetch a file /*{{{*/
  28. // ---------------------------------------------------------------------
  29. /* */
  30. bool CopyMethod::Fetch(FetchItem *Itm)
  31. {
  32. URI Get = Itm->Uri;
  33. std::string File = Get.Path;
  34. // Stat the file and send a start message
  35. struct stat Buf;
  36. if (stat(File.c_str(),&Buf) != 0)
  37. return _error->Errno("stat",_("Failed to stat"));
  38. // Forumulate a result and send a start message
  39. FetchResult Res;
  40. Res.Size = Buf.st_size;
  41. Res.Filename = Itm->DestFile;
  42. Res.LastModified = Buf.st_mtime;
  43. Res.IMSHit = false;
  44. URIStart(Res);
  45. // See if the file exists
  46. FileFd From(File,FileFd::ReadOnly);
  47. FileFd To(Itm->DestFile,FileFd::WriteAtomic);
  48. To.EraseOnFailure();
  49. if (_error->PendingError() == true)
  50. {
  51. To.OpFail();
  52. return false;
  53. }
  54. // Copy the file
  55. if (CopyFile(From,To) == false)
  56. {
  57. To.OpFail();
  58. return false;
  59. }
  60. From.Close();
  61. To.Close();
  62. // Transfer the modification times
  63. struct timeval times[2];
  64. times[0].tv_sec = Buf.st_atime;
  65. times[1].tv_sec = Buf.st_mtime;
  66. times[0].tv_usec = times[1].tv_usec = 0;
  67. if (utimes(Res.Filename.c_str(), times) != 0)
  68. return _error->Errno("utimes",_("Failed to set modification time"));
  69. Hashes Hash;
  70. FileFd Fd(Res.Filename, FileFd::ReadOnly);
  71. Hash.AddFD(Fd);
  72. Res.TakeHashes(Hash);
  73. URIDone(Res);
  74. return true;
  75. }
  76. /*}}}*/
  77. int main()
  78. {
  79. setlocale(LC_ALL, "");
  80. CopyMethod Mth;
  81. return Mth.Run();
  82. }