copy.cc 2.4 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 <config.h>
  11. #include <apt-pkg/fileutl.h>
  12. #include <apt-pkg/strutl.h>
  13. #include <apt-pkg/error.h>
  14. #include <apt-pkg/hashes.h>
  15. #include <apt-pkg/configuration.h>
  16. #include "aptmethod.h"
  17. #include <string>
  18. #include <sys/stat.h>
  19. #include <sys/time.h>
  20. #include <apti18n.h>
  21. /*}}}*/
  22. class CopyMethod : public aptMethod
  23. {
  24. virtual bool Fetch(FetchItem *Itm) APT_OVERRIDE;
  25. public:
  26. CopyMethod() : aptMethod("copy", "1.0",SingleInstance | SendConfig) {};
  27. };
  28. // CopyMethod::Fetch - Fetch a file /*{{{*/
  29. // ---------------------------------------------------------------------
  30. /* */
  31. bool CopyMethod::Fetch(FetchItem *Itm)
  32. {
  33. // this ensures that relative paths work in copy
  34. std::string const File = Itm->Uri.substr(Itm->Uri.find(':')+1);
  35. // Stat the file and send a start message
  36. struct stat Buf;
  37. if (stat(File.c_str(),&Buf) != 0)
  38. return _error->Errno("stat",_("Failed to stat"));
  39. // Forumulate a result and send a start message
  40. FetchResult Res;
  41. Res.Size = Buf.st_size;
  42. Res.Filename = Itm->DestFile;
  43. Res.LastModified = Buf.st_mtime;
  44. Res.IMSHit = false;
  45. URIStart(Res);
  46. // just calc the hashes if the source and destination are identical
  47. if (File == Itm->DestFile || Itm->DestFile == "/dev/null")
  48. {
  49. CalculateHashes(Itm, Res);
  50. URIDone(Res);
  51. return true;
  52. }
  53. // See if the file exists
  54. FileFd From(File,FileFd::ReadOnly);
  55. FileFd To(Itm->DestFile,FileFd::WriteAtomic);
  56. To.EraseOnFailure();
  57. // Copy the file
  58. if (CopyFile(From,To) == false)
  59. {
  60. To.OpFail();
  61. return false;
  62. }
  63. From.Close();
  64. To.Close();
  65. // Transfer the modification times
  66. struct timeval times[2];
  67. times[0].tv_sec = Buf.st_atime;
  68. times[1].tv_sec = Buf.st_mtime;
  69. times[0].tv_usec = times[1].tv_usec = 0;
  70. if (utimes(Res.Filename.c_str(), times) != 0)
  71. return _error->Errno("utimes",_("Failed to set modification time"));
  72. CalculateHashes(Itm, Res);
  73. URIDone(Res);
  74. return true;
  75. }
  76. /*}}}*/
  77. int main()
  78. {
  79. return CopyMethod().Run();
  80. }