copy.cc 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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 <apt-pkg/fileutl.h>
  11. #include <apt-pkg/acquire-method.h>
  12. #include <apt-pkg/error.h>
  13. #include <apt-pkg/hashes.h>
  14. #include <sys/stat.h>
  15. #include <utime.h>
  16. #include <unistd.h>
  17. #include <apti18n.h>
  18. /*}}}*/
  19. class CopyMethod : public pkgAcqMethod
  20. {
  21. virtual bool Fetch(FetchItem *Itm);
  22. public:
  23. CopyMethod() : pkgAcqMethod("1.0",SingleInstance) {};
  24. };
  25. // CopyMethod::Fetch - Fetch a file /*{{{*/
  26. // ---------------------------------------------------------------------
  27. /* */
  28. bool CopyMethod::Fetch(FetchItem *Itm)
  29. {
  30. URI Get = Itm->Uri;
  31. string File = Get.Path;
  32. // Stat the file and send a start message
  33. struct stat Buf;
  34. if (stat(File.c_str(),&Buf) != 0)
  35. return _error->Errno("stat",_("Failed to stat"));
  36. // Forumulate a result and send a start message
  37. FetchResult Res;
  38. Res.Size = Buf.st_size;
  39. Res.Filename = Itm->DestFile;
  40. Res.LastModified = Buf.st_mtime;
  41. Res.IMSHit = false;
  42. URIStart(Res);
  43. // See if the file exists
  44. FileFd From(File,FileFd::ReadOnly);
  45. FileFd To(Itm->DestFile,FileFd::WriteEmpty);
  46. To.EraseOnFailure();
  47. if (_error->PendingError() == true)
  48. {
  49. To.OpFail();
  50. return false;
  51. }
  52. // Copy the file
  53. if (CopyFile(From,To) == false)
  54. {
  55. To.OpFail();
  56. return false;
  57. }
  58. From.Close();
  59. To.Close();
  60. // Transfer the modification times
  61. struct utimbuf TimeBuf;
  62. TimeBuf.actime = Buf.st_atime;
  63. TimeBuf.modtime = Buf.st_mtime;
  64. if (utime(Itm->DestFile.c_str(),&TimeBuf) != 0)
  65. {
  66. To.OpFail();
  67. return _error->Errno("utime",_("Failed to set modification time"));
  68. }
  69. Hashes Hash;
  70. FileFd Fd(Res.Filename, FileFd::ReadOnly);
  71. Hash.AddFD(Fd.Fd(), Fd.Size());
  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. }