copy.cc 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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 <sys/stat.h>
  17. #include <utime.h>
  18. #include <unistd.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 utimbuf TimeBuf;
  64. TimeBuf.actime = Buf.st_atime;
  65. TimeBuf.modtime = Buf.st_mtime;
  66. if (utime(Itm->DestFile.c_str(),&TimeBuf) != 0)
  67. {
  68. To.OpFail();
  69. return _error->Errno("utime",_("Failed to set modification time"));
  70. }
  71. Hashes Hash;
  72. FileFd Fd(Res.Filename, FileFd::ReadOnly);
  73. Hash.AddFD(Fd);
  74. Res.TakeHashes(Hash);
  75. URIDone(Res);
  76. return true;
  77. }
  78. /*}}}*/
  79. int main()
  80. {
  81. setlocale(LC_ALL, "");
  82. CopyMethod Mth;
  83. return Mth.Run();
  84. }