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