- decision to do refresh moved to a public checkIfToRefreshMetadata()
[platform/upstream/libzypp.git] / zypp / RepoManager.cc
1 /*---------------------------------------------------------------------\
2 |                          ____ _   __ __ ___                          |
3 |                         |__  / \ / / . \ . \                         |
4 |                           / / \ V /|  _/  _/                         |
5 |                          / /__ | | | | | |                           |
6 |                         /_____||_| |_| |_|                           |
7 |                                                                      |
8 \---------------------------------------------------------------------*/
9 /** \file       zypp/RepoManager.cc
10  *
11 */
12
13 #include <iostream>
14 #include <fstream>
15 #include <list>
16 #include <algorithm>
17 #include "zypp/base/InputStream.h"
18 #include "zypp/base/Logger.h"
19 #include "zypp/base/Gettext.h"
20 #include "zypp/base/Function.h"
21 #include "zypp/PathInfo.h"
22 #include "zypp/TmpPath.h"
23
24 #include "zypp/repo/RepoException.h"
25 #include "zypp/RepoManager.h"
26
27 #include "zypp/cache/CacheStore.h"
28 #include "zypp/repo/cached/RepoImpl.h"
29 #include "zypp/media/MediaManager.h"
30 #include "zypp/MediaSetAccess.h"
31
32 #include "zypp/parser/RepoFileReader.h"
33 #include "zypp/repo/yum/Downloader.h"
34 #include "zypp/parser/yum/RepoParser.h"
35 #include "zypp/parser/plaindir/RepoParser.h"
36 #include "zypp/repo/susetags/Downloader.h"
37 #include "zypp/parser/susetags/RepoParser.h"
38
39 #include "zypp/ZYppCallbacks.h"
40
41 using namespace std;
42 using namespace zypp;
43 using namespace zypp::repo;
44 using namespace zypp::filesystem;
45
46 using namespace zypp::repo;
47
48 ///////////////////////////////////////////////////////////////////
49 namespace zypp
50 { /////////////////////////////////////////////////////////////////
51
52   ///////////////////////////////////////////////////////////////////
53   //
54   //    CLASS NAME : RepoManagerOptions
55   //
56   ///////////////////////////////////////////////////////////////////
57
58   RepoManagerOptions::RepoManagerOptions()
59   {
60     repoCachePath    = ZConfig::instance().repoCachePath();
61     repoRawCachePath = ZConfig::instance().repoMetadataPath();
62     knownReposPath   = ZConfig::instance().knownReposPath();
63   }
64
65   ////////////////////////////////////////////////////////////////////////////
66
67   /**
68     * \short Simple callback to collect the results
69     *
70     * Classes like RepoFileParser call the callback
71     * once per each repo in a file.
72     *
73     * Passing this functor as callback, you can collect
74     * all resuls at the end, without dealing with async
75     * code.
76     */
77     struct RepoCollector
78     {
79       RepoCollector()
80       {
81         MIL << endl;
82       }
83
84       ~RepoCollector()
85       {
86         MIL << endl;
87       }
88
89       bool collect( const RepoInfo &repo )
90       {
91         //MIL << "here in collector: " << repo.alias() << endl;
92         repos.push_back(repo);
93         //MIL << "added: " << repo.alias() << endl;
94         return true;
95       }
96
97       RepoInfoList repos;
98     };
99
100   ////////////////////////////////////////////////////////////////////////////
101
102    /**
103     * \short Internal version of clean cache
104     *
105     * Takes an extra CacheStore reference, so we avoid internally
106     * having 2 CacheStores writing to the same database.
107     */
108   static void cleanCacheInternal( cache::CacheStore &store,
109                                   const RepoInfo &info,
110                                   const ProgressData::ReceiverFnc & progressrcv = ProgressData::ReceiverFnc() )
111   {
112     ProgressData progress;
113     callback::SendReport<ProgressReport> report;
114     progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
115     progress.name(str::form(_("Cleaning repository '%s' cache"), info.name().c_str()));
116
117     if ( !store.isCached(info.alias()) )
118       return;
119    
120     MIL << info.alias() << " cleaning cache..." << endl;
121     data::RecordId id = store.lookupRepository(info.alias());
122     
123     CombinedProgressData subprogrcv(progress);
124     
125     store.cleanRepository(id, subprogrcv);
126   }
127   
128   ////////////////////////////////////////////////////////////////////////////
129   
130   /**
131    * Reads RepoInfo's from a repo file.
132    *
133    * \param file pathname of the file to read.
134    */
135   static std::list<RepoInfo> repositories_in_file( const Pathname & file )
136   {
137     MIL << "repo file: " << file << endl;
138     RepoCollector collector;
139     parser::RepoFileReader parser( file, bind( &RepoCollector::collect, &collector, _1 ) );
140     return collector.repos;
141   }
142
143   ////////////////////////////////////////////////////////////////////////////
144
145   std::list<RepoInfo> readRepoFile(const Url & repo_file)
146    {
147      // no interface to download a specific file, using workaround:
148      //! \todo add MediaManager::provideFile(Url file_url) to easily access any file URLs? (no need for media access id or media_nr)
149      Url url(repo_file);
150      Pathname path(url.getPathName());
151      url.setPathName ("/");
152      MediaSetAccess access(url);
153      Pathname local = access.provideFile(path);
154
155      DBG << "reading repo file " << repo_file << ", local path: " << local << endl;
156
157      return repositories_in_file(local);
158    }
159
160   ////////////////////////////////////////////////////////////////////////////
161
162   /**
163    * \short List of RepoInfo's from a directory
164    *
165    * Goes trough every file in a directory and adds all
166    * RepoInfo's contained in that file.
167    *
168    * \param dir pathname of the directory to read.
169    */
170   static std::list<RepoInfo> repositories_in_dir( const Pathname &dir )
171   {
172     MIL << "directory " << dir << endl;
173     list<RepoInfo> repos;
174     list<Pathname> entries;
175     if ( filesystem::readdir( entries, Pathname(dir), false ) != 0 )
176       ZYPP_THROW(Exception("failed to read directory"));
177
178     for ( list<Pathname>::const_iterator it = entries.begin(); it != entries.end(); ++it )
179     {
180       list<RepoInfo> tmp = repositories_in_file( *it );
181       repos.insert( repos.end(), tmp.begin(), tmp.end() );
182
183       //std::copy( collector.repos.begin(), collector.repos.end(), std::back_inserter(repos));
184       //MIL << "ok" << endl;
185     }
186     return repos;
187   }
188
189   ////////////////////////////////////////////////////////////////////////////
190
191   static void assert_alias( const RepoInfo &info )
192   {
193     if (info.alias().empty())
194         ZYPP_THROW(RepoNoAliasException());
195   }
196
197   ////////////////////////////////////////////////////////////////////////////
198
199   static void assert_urls( const RepoInfo &info )
200   {
201     if (info.baseUrlsEmpty())
202         ZYPP_THROW(RepoNoUrlException());
203   }
204
205   ////////////////////////////////////////////////////////////////////////////
206
207   /**
208    * \short Calculates the raw cache path for a repository
209    */
210   static Pathname rawcache_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info )
211   {
212     assert_alias(info);
213     return opt.repoRawCachePath + info.alias();
214   }
215
216   ///////////////////////////////////////////////////////////////////
217   //
218   //    CLASS NAME : RepoManager::Impl
219   //
220   ///////////////////////////////////////////////////////////////////
221
222   /**
223    * \short RepoManager implementation.
224    */
225   struct RepoManager::Impl
226   {
227     Impl( const RepoManagerOptions &opt )
228       : options(opt)
229     {
230
231     }
232
233     Impl()
234     {
235
236     }
237
238     RepoManagerOptions options;
239
240   public:
241     /** Offer default Impl. */
242     static shared_ptr<Impl> nullimpl()
243     {
244       static shared_ptr<Impl> _nullimpl( new Impl );
245       return _nullimpl;
246     }
247
248   private:
249     friend Impl * rwcowClone<Impl>( const Impl * rhs );
250     /** clone for RWCOW_pointer */
251     Impl * clone() const
252     { return new Impl( *this ); }
253   };
254   ///////////////////////////////////////////////////////////////////
255
256   /** \relates RepoManager::Impl Stream output */
257   inline std::ostream & operator<<( std::ostream & str, const RepoManager::Impl & obj )
258   {
259     return str << "RepoManager::Impl";
260   }
261
262   ///////////////////////////////////////////////////////////////////
263   //
264   //    CLASS NAME : RepoManager
265   //
266   ///////////////////////////////////////////////////////////////////
267
268   RepoManager::RepoManager( const RepoManagerOptions &opt )
269   : _pimpl( new Impl(opt) )
270   {}
271
272   ////////////////////////////////////////////////////////////////////////////
273
274   RepoManager::~RepoManager()
275   {}
276
277   ////////////////////////////////////////////////////////////////////////////
278
279   std::list<RepoInfo> RepoManager::knownRepositories() const
280   {
281     MIL << endl;
282
283     if ( PathInfo(_pimpl->options.knownReposPath).isExist() )
284     {
285       RepoInfoList repos = repositories_in_dir(_pimpl->options.knownReposPath);
286       for ( RepoInfoList::iterator it = repos.begin();
287             it != repos.end();
288             ++it )
289       {
290         // set the metadata path for the repo
291         Pathname metadata_path = rawcache_path_for_repoinfo(_pimpl->options, (*it));
292         (*it).setMetadataPath(metadata_path);
293       }
294       return repos;
295     }
296     else
297       return std::list<RepoInfo>();
298
299     MIL << endl;
300   }
301
302   ////////////////////////////////////////////////////////////////////////////
303
304   RepoStatus RepoManager::metadataStatus( const RepoInfo &info ) const
305   {
306     Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
307     RepoType repokind = info.type();
308     RepoStatus status;
309
310     switch ( repokind.toEnum() )
311     {
312       case RepoType::NONE_e:
313       // unknown, probe the local metadata
314         repokind = probe(rawpath.asUrl());
315       break;
316       default:
317       break;
318     }
319
320     switch ( repokind.toEnum() )
321     {
322       case RepoType::RPMMD_e :
323       {
324         status = RepoStatus( rawpath + "/repodata/repomd.xml");
325       }
326       break;
327
328       case RepoType::YAST2_e :
329       {
330         status = RepoStatus( rawpath + "/content");
331       }
332       break;
333
334       case RepoType::RPMPLAINDIR_e :
335       {
336         if ( PathInfo(Pathname(rawpath + "/cookie")).isExist() )
337           status = RepoStatus( rawpath + "/cookie");
338       }
339       break;
340
341       case RepoType::NONE_e :
342         // Return default RepoStatus in case of RepoType::NONE
343         // indicating it should be created?
344         // ZYPP_THROW(RepoUnknownTypeException());
345         break;
346     }
347     return status;
348   }
349
350   bool RepoManager::checkIfToRefreshMetadata( const RepoInfo &info,
351                                               const Url &url,
352                                               RawMetadataRefreshPolicy policy )
353   {
354     assert_alias(info);
355
356     RepoStatus oldstatus;
357     RepoStatus newstatus;
358
359     try
360     {
361       MIL << "Going to try to check whether refresh is needed for " << url << endl;
362
363       repo::RepoType repokind = info.type();
364
365       // if the type is unknown, try probing.
366       switch ( repokind.toEnum() )
367       {
368         case RepoType::NONE_e:
369           // unknown, probe it
370           repokind = probe(url);
371         break;
372         default:
373         break;
374       }
375
376       Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
377       filesystem::assert_dir(rawpath);
378       oldstatus = metadataStatus(info);
379       
380       // create temp dir as sibling of rawpath
381       filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( rawpath ) );
382
383       if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
384            ( repokind.toEnum() == RepoType::YAST2_e ) )
385       {
386         MediaSetAccess media(url);
387         shared_ptr<repo::Downloader> downloader_ptr;
388
389         if ( repokind.toEnum() == RepoType::RPMMD_e )
390           downloader_ptr.reset(new yum::Downloader(info.path()));
391         else
392           downloader_ptr.reset( new susetags::Downloader(info.path()));
393
394         RepoStatus newstatus = downloader_ptr->status(media);
395         bool refresh = false;
396         if ( oldstatus.checksum() == newstatus.checksum() )
397         {
398           MIL << "repo has not changed" << endl;
399           if ( policy == RefreshForced )
400           {
401             MIL << "refresh set to forced" << endl;
402             refresh = true;
403           }
404         }
405         else
406         {
407           MIL << "repo has changed, going to refresh" << endl;
408           refresh = true;
409         }
410
411         return refresh;
412       }
413       else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
414       {
415         RepoStatus newstatus = parser::plaindir::dirStatus(url.getPathName());
416         bool refresh = false;
417         if ( oldstatus.checksum() == newstatus.checksum() )
418         {
419           MIL << "repo has not changed" << endl;
420           if ( policy == RefreshForced )
421           {
422             MIL << "refresh set to forced" << endl;
423             refresh = true;
424           }
425         }
426         else
427         {
428           MIL << "repo has changed, going to refresh" << endl;
429           refresh = true;
430         }
431
432         return refresh;
433       }
434       else
435       {
436         ZYPP_THROW(RepoUnknownTypeException());
437       }
438     }
439     catch ( const Exception &e )
440     {
441       ZYPP_CAUGHT(e);
442       ERR << "refresh check failed for " << url << endl;
443       ZYPP_RETHROW(e);
444     }
445     
446     return true; // default
447   }
448
449   void RepoManager::refreshMetadata( const RepoInfo &info,
450                                      RawMetadataRefreshPolicy policy,
451                                      const ProgressData::ReceiverFnc & progress )
452   {
453     assert_alias(info);
454     assert_urls(info);
455
456     // try urls one by one
457     for ( RepoInfo::urls_const_iterator it = info.baseUrlsBegin(); it != info.baseUrlsEnd(); ++it )
458     {
459       try
460       {
461         Url url(*it);
462
463         // check whether to refresh metadata
464         // if the check fails for this url, it throws, so another url will be checked
465         if (!checkIfToRefreshMetadata(info, url, policy))
466           return;
467
468         MIL << "Going to refresh metadata from " << url << endl;
469
470         repo::RepoType repokind = info.type();
471
472         // if the type is unknown, try probing.
473         switch ( repokind.toEnum() )
474         {
475           case RepoType::NONE_e:
476             // unknown, probe it
477             repokind = probe(*it);
478           break;
479           default:
480           break;
481         }
482
483         Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
484         filesystem::assert_dir(rawpath);
485
486         // create temp dir as sibling of rawpath
487         filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( rawpath ) );
488
489         if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
490              ( repokind.toEnum() == RepoType::YAST2_e ) )
491         {
492           MediaSetAccess media(url);
493           shared_ptr<repo::Downloader> downloader_ptr;
494
495           if ( repokind.toEnum() == RepoType::RPMMD_e )
496             downloader_ptr.reset(new yum::Downloader(info.path()));
497           else
498             downloader_ptr.reset( new susetags::Downloader(info.path()));
499
500           /**
501            * Given a downloader, sets the other repos raw metadata
502            * path as cache paths for the fetcher, so if another
503            * repo has the same file, it will not download it
504            * but copy it from the other repository
505            */
506           std::list<RepoInfo> repos = knownRepositories();
507           for ( std::list<RepoInfo>::const_iterator it = repos.begin();
508                 it != repos.end();
509                 ++it )
510           {
511             downloader_ptr->addCachePath(rawcache_path_for_repoinfo( _pimpl->options, *it ));
512           }
513
514           downloader_ptr->download( media, tmpdir.path());
515         }
516         else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
517         {
518           RepoStatus newstatus = parser::plaindir::dirStatus(url.getPathName());
519
520           std::ofstream file(( tmpdir.path() + "/cookie").c_str());
521           if (!file) {
522             ZYPP_THROW (Exception( "Can't open " + tmpdir.path().asString() + "/cookie" ) );
523           }
524           file << url << endl;
525           file << newstatus.checksum() << endl;
526
527           file.close();
528         }
529         else
530         {
531           ZYPP_THROW(RepoUnknownTypeException());
532         }
533
534         // ok we have the metadata, now exchange
535         // the contents
536         TmpDir oldmetadata( TmpDir::makeSibling( rawpath ) );
537         filesystem::rename( rawpath, oldmetadata.path() );
538         // move the just downloaded there
539         filesystem::rename( tmpdir.path(), rawpath );
540         // we are done.
541         return;
542       }
543       catch ( const Exception &e )
544       {
545         ZYPP_CAUGHT(e);
546         ERR << "Trying another url..." << endl;
547       }
548     } // for every url
549     ERR << "No more urls..." << endl;
550     ZYPP_THROW(RepoException(_("Valid metadata not found at specified URL(s)")));
551   }
552
553   ////////////////////////////////////////////////////////////////////////////
554
555   void RepoManager::cleanMetadata( const RepoInfo &info,
556                                    const ProgressData::ReceiverFnc & progress )
557   {
558     filesystem::recursive_rmdir(rawcache_path_for_repoinfo(_pimpl->options, info));
559   }
560
561   void RepoManager::buildCache( const RepoInfo &info,
562                                 CacheBuildPolicy policy,
563                                 const ProgressData::ReceiverFnc & progressrcv )
564   {
565     assert_alias(info);
566     Pathname rawpath = rawcache_path_for_repoinfo(_pimpl->options, info);
567
568     cache::CacheStore store(_pimpl->options.repoCachePath);
569
570     RepoStatus raw_metadata_status = metadataStatus(info);
571     if ( raw_metadata_status.empty() )
572     {
573       ZYPP_THROW(RepoMetadataException(info));
574     }
575
576     bool needs_cleaning = false;
577     if ( store.isCached( info.alias() ) )
578     {
579       MIL << info.alias() << " is already cached." << endl;
580       data::RecordId id = store.lookupRepository(info.alias());
581       RepoStatus cache_status = store.repositoryStatus(id);
582
583       if ( cache_status.checksum() == raw_metadata_status.checksum() )
584       {
585         MIL << info.alias() << " cache is up to date with metadata." << endl;
586         if ( policy == BuildIfNeeded ) {
587           return;
588         }
589         else {
590           MIL << info.alias() << " cache rebuild is forced" << endl;
591         }
592       }
593       
594       needs_cleaning = true;
595     }
596
597     ProgressData progress(100);
598     callback::SendReport<ProgressReport> report;
599     progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
600     progress.name(str::form(_("Building repository '%s' cache"), info.name().c_str()));
601     progress.toMin();
602
603     if (needs_cleaning)
604       cleanCacheInternal( store, info);
605
606     MIL << info.alias() << " building cache..." << endl;
607     data::RecordId id = store.lookupOrAppendRepository(info.alias());
608     // do we have type?
609     repo::RepoType repokind = info.type();
610
611     // if the type is unknown, try probing.
612     switch ( repokind.toEnum() )
613     {
614       case RepoType::NONE_e:
615         // unknown, probe the local metadata
616         repokind = probe(rawpath.asUrl());
617       break;
618       default:
619       break;
620     }
621
622     
623     switch ( repokind.toEnum() )
624     {
625       case RepoType::RPMMD_e :
626       {
627         CombinedProgressData subprogrcv( progress, 100);
628         parser::yum::RepoParser parser(id, store, parser::yum::RepoParserOpts(), subprogrcv);
629         parser.parse(rawpath);
630           // no error
631       }
632       break;
633       case RepoType::YAST2_e :
634       {
635         CombinedProgressData subprogrcv( progress, 100);
636         parser::susetags::RepoParser parser(id, store, subprogrcv);
637         parser.parse(rawpath);
638         // no error
639       }
640       break;
641       case RepoType::RPMPLAINDIR_e :
642       {
643         CombinedProgressData subprogrcv( progress, 100);
644         InputStream is(rawpath + "cookie");
645         string buffer;
646         getline( is.stream(), buffer);
647         Url url(buffer);
648         parser::plaindir::RepoParser parser(id, store, subprogrcv);
649         parser.parse(url.getPathName());
650       }
651       break;
652       default:
653         ZYPP_THROW(RepoUnknownTypeException());
654     }
655
656     // update timestamp and checksum
657     store.updateRepositoryStatus(id, raw_metadata_status);
658
659     MIL << "Commit cache.." << endl;
660     store.commit();
661     //progress.toMax();
662   }
663
664   ////////////////////////////////////////////////////////////////////////////
665
666   repo::RepoType RepoManager::probe( const Url &url ) const
667   {
668     if ( url.getScheme() == "dir" && ! PathInfo( url.getPathName() ).isDir() )
669     {
670       // Handle non existing local directory in advance, as
671       // MediaSetAccess does not support it.
672       return repo::RepoType::NONE;
673     }
674
675     try
676     {
677       MediaSetAccess access(url);
678       if ( access.doesFileExist("/repodata/repomd.xml") )
679         return repo::RepoType::RPMMD;
680       if ( access.doesFileExist("/content") )
681         return repo::RepoType::YAST2;
682   
683       // if it is a local url of type dir
684       if ( (! media::MediaManager::downloads(url)) && ( url.getScheme() == "dir" ) )
685       {
686         Pathname path = Pathname(url.getPathName());
687         if ( PathInfo(path).isDir() )
688         {
689           // allow empty dirs for now
690           return repo::RepoType::RPMPLAINDIR;
691         }
692       }
693     }
694     catch ( const media::MediaException &e )
695     {
696       ZYPP_CAUGHT(e);
697       RepoException enew("Error trying to read from " + url.asString());
698       enew.remember(e);
699       ZYPP_THROW(enew);
700     }
701     catch ( const Exception &e )
702     {
703       ZYPP_CAUGHT(e);
704       Exception enew("Unknown error reading from " + url.asString());
705       enew.remember(e);
706       ZYPP_THROW(enew);
707     }
708
709     return repo::RepoType::NONE;
710   }
711     
712   ////////////////////////////////////////////////////////////////////////////
713   
714   void RepoManager::cleanCache( const RepoInfo &info,
715                                 const ProgressData::ReceiverFnc & progressrcv )
716   {
717     cache::CacheStore store(_pimpl->options.repoCachePath);
718     cleanCacheInternal( store, info, progressrcv );
719     store.commit();
720   }
721
722   ////////////////////////////////////////////////////////////////////////////
723
724   bool RepoManager::isCached( const RepoInfo &info ) const
725   {
726     cache::CacheStore store(_pimpl->options.repoCachePath);
727     return store.isCached(info.alias());
728   }
729
730   RepoStatus RepoManager::cacheStatus( const RepoInfo &info ) const
731   {
732     cache::CacheStore store(_pimpl->options.repoCachePath);
733     data::RecordId id = store.lookupRepository(info.alias());
734     RepoStatus cache_status = store.repositoryStatus(id);
735     return cache_status;
736   }
737
738   Repository RepoManager::createFromCache( const RepoInfo &info,
739                                            const ProgressData::ReceiverFnc & progressrcv )
740   {
741     callback::SendReport<ProgressReport> report;
742     ProgressData progress;
743     progress.sendTo(ProgressReportAdaptor( progressrcv, report ));
744     //progress.sendTo( progressrcv );
745     progress.name(str::form(_("Reading repository '%s' cache"), info.name().c_str()));
746     
747     cache::CacheStore store(_pimpl->options.repoCachePath);
748
749     if ( ! store.isCached( info.alias() ) )
750       ZYPP_THROW(RepoNotCachedException());
751
752     MIL << "Repository " << info.alias() << " is cached" << endl;
753
754     data::RecordId id = store.lookupRepository(info.alias());
755     
756     CombinedProgressData subprogrcv(progress);
757     
758     repo::cached::RepoOptions opts( info, _pimpl->options.repoCachePath, id );
759     opts.readingResolvablesProgress = subprogrcv;
760     repo::cached::RepoImpl::Ptr repoimpl =
761         new repo::cached::RepoImpl( opts );
762
763     repoimpl->resolvables();
764     // read the resolvables from cache
765     return Repository(repoimpl);
766   }
767
768   ////////////////////////////////////////////////////////////////////////////
769
770   /**
771    * Generate a non existing filename in a directory, using a base
772    * name. For example if a directory contains 3 files
773    *
774    * |-- bar
775    * |-- foo
776    * `-- moo
777    *
778    * If you try to generate a unique filename for this directory,
779    * based on "ruu" you will get "ruu", but if you use the base
780    * "foo" you will get "foo_1"
781    *
782    * \param dir Directory where the file needs to be unique
783    * \param basefilename string to base the filename on.
784    */
785   static Pathname generate_non_existing_name( const Pathname &dir,
786                                               const std::string &basefilename )
787   {
788     string final_filename = basefilename;
789     int counter = 1;
790     while ( PathInfo(dir + final_filename).isExist() )
791     {
792       final_filename = basefilename + "_" + str::numstring(counter);
793       counter++;
794     }
795     return dir + Pathname(final_filename);
796   }
797
798   ////////////////////////////////////////////////////////////////////////////
799
800   /**
801    * \short Generate a related filename from a repo info
802    *
803    * From a repo info, it will try to use the alias as a filename
804    * escaping it if necessary. Other fallbacks can be added to
805    * this function in case there is no way to use the alias
806    */
807   static std::string generate_filename( const RepoInfo &info )
808   {
809     std::string fnd="/";
810     std::string rep="_";
811     std::string filename = info.alias();
812     // replace slashes with underscores
813     size_t pos = filename.find(fnd);
814     while(pos!=string::npos)
815     {
816       filename.replace(pos,fnd.length(),rep);
817       pos = filename.find(fnd,pos+rep.length());
818     }
819     filename = Pathname(filename).extend(".repo").asString();
820     MIL << "generating filename for repo [" << info.alias() << "] : '" << filename << "'" << endl;
821     return filename;
822   }
823
824
825   ////////////////////////////////////////////////////////////////////////////
826
827   void RepoManager::addRepository( const RepoInfo &info,
828                                    const ProgressData::ReceiverFnc & progressrcv )
829   {
830     assert_alias(info);
831
832     ProgressData progress(100);
833     callback::SendReport<ProgressReport> report;
834     progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
835     progress.name(str::form(_("Adding repository '%s'"), info.name().c_str()));
836     progress.toMin();
837
838     std::list<RepoInfo> repos = knownRepositories();
839     for ( std::list<RepoInfo>::const_iterator it = repos.begin();
840           it != repos.end();
841           ++it )
842     {
843       if ( info.alias() == (*it).alias() )
844         ZYPP_THROW(RepoAlreadyExistsException(info.alias()));
845     }
846
847     RepoInfo tosave = info;
848     
849     // check the first url for now
850     if ( ZConfig::instance().repo_add_probe() || ( tosave.type() == RepoType::NONE ) )
851     {
852       RepoType probedtype;
853       probedtype = probe(*tosave.baseUrlsBegin());
854       if ( tosave.baseUrlsSize() > 0 )
855       {
856         if ( probedtype == RepoType::NONE )
857           ZYPP_THROW(RepoUnknownTypeException());
858         else
859           tosave.setType(probedtype);
860       }
861     }
862     
863     progress.set(50);
864
865     // assert the directory exists
866     filesystem::assert_dir(_pimpl->options.knownReposPath);
867
868     Pathname repofile = generate_non_existing_name(_pimpl->options.knownReposPath,
869                                                     generate_filename(tosave));
870     // now we have a filename that does not exists
871     MIL << "Saving repo in " << repofile << endl;
872
873     std::ofstream file(repofile.c_str());
874     if (!file) {
875       ZYPP_THROW (Exception( "Can't open " + repofile.asString() ) );
876     }
877
878     tosave.dumpRepoOn(file);
879     progress.toMax();
880     MIL << "done" << endl;
881   }
882
883   void RepoManager::addRepositories( const Url &url,
884                                      const ProgressData::ReceiverFnc & progressrcv )
885   {
886     std::list<RepoInfo> knownrepos = knownRepositories();
887     std::list<RepoInfo> repos = readRepoFile(url);
888     for ( std::list<RepoInfo>::const_iterator it = repos.begin();
889           it != repos.end();
890           ++it )
891     {
892       // look if the alias is in the known repos.
893       for ( std::list<RepoInfo>::const_iterator kit = knownrepos.begin();
894           kit != knownrepos.end();
895           ++kit )
896       {
897         if ( (*it).alias() == (*kit).alias() )
898         {
899           ERR << "To be added repo " << (*it).alias() << " conflicts with existing repo " << (*kit).alias() << endl;
900           ZYPP_THROW(RepoAlreadyExistsException((*it).alias()));
901         }
902       }
903     }
904
905     string filename = Pathname(url.getPathName()).basename();
906
907     if ( filename == Pathname() )
908       ZYPP_THROW(RepoException("Invalid repo file name at " + url.asString() ));
909
910     // assert the directory exists
911     filesystem::assert_dir(_pimpl->options.knownReposPath);
912
913     Pathname repofile = generate_non_existing_name(_pimpl->options.knownReposPath, filename);
914     // now we have a filename that does not exists
915     MIL << "Saving " << repos.size() << " repo" << ( repos.size() ? "s" : "" ) << " in " << repofile << endl;
916
917     std::ofstream file(repofile.c_str());
918     if (!file) {
919       ZYPP_THROW (Exception( "Can't open " + repofile.asString() ) );
920     }
921
922     for ( std::list<RepoInfo>::const_iterator it = repos.begin();
923           it != repos.end();
924           ++it )
925     {
926       MIL << "Saving " << (*it).alias() << endl;
927       (*it).dumpRepoOn(file);
928     }
929     MIL << "done" << endl;
930   }
931
932   ////////////////////////////////////////////////////////////////////////////
933
934   void RepoManager::removeRepository( const RepoInfo & info,
935                                       const ProgressData::ReceiverFnc & progressrcv)
936   {
937     ProgressData progress;
938     callback::SendReport<ProgressReport> report;
939     progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
940     progress.name(str::form(_("Removing repository '%s'"), info.name().c_str()));
941     
942     MIL << "Going to delete repo " << info.alias() << endl;
943
944     std::list<RepoInfo> repos = knownRepositories();
945     for ( std::list<RepoInfo>::const_iterator it = repos.begin();
946           it != repos.end();
947           ++it )
948     {
949       // they can be the same only if the provided is empty, that means
950       // the provided repo has no alias
951       // then skip
952       if ( (!info.alias().empty()) && ( info.alias() != (*it).alias() ) )
953         continue;
954
955       // TODO match by url
956
957       // we have a matcing repository, now we need to know
958       // where it does come from.
959       RepoInfo todelete = *it;
960       if (todelete.filepath().empty())
961       {
962         ZYPP_THROW(RepoException("Can't figure where the repo is stored"));
963       }
964       else
965       {
966         // figure how many repos are there in the file:
967         std::list<RepoInfo> filerepos = repositories_in_file(todelete.filepath());
968         if ( (filerepos.size() == 1) && ( filerepos.front().alias() == todelete.alias() ) )
969         {
970           // easy, only this one, just delete the file
971           if ( filesystem::unlink(todelete.filepath()) != 0 )
972           {
973             ZYPP_THROW(RepoException("Can't delete " + todelete.filepath().asString()));
974           }
975           MIL << todelete.alias() << " sucessfully deleted." << endl;
976         }
977         else
978         {
979           // there are more repos in the same file
980           // write them back except the deleted one.
981           //TmpFile tmp;
982           //std::ofstream file(tmp.path().c_str());
983
984           // assert the directory exists
985           filesystem::assert_dir(todelete.filepath().dirname());
986
987           std::ofstream file(todelete.filepath().c_str());
988           if (!file) {
989             //ZYPP_THROW (Exception( "Can't open " + tmp.path().asString() ) );
990             ZYPP_THROW (Exception( "Can't open " + todelete.filepath().asString() ) );
991           }
992           for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
993                 fit != filerepos.end();
994                 ++fit )
995           {
996             if ( (*fit).alias() != todelete.alias() )
997               (*fit).dumpRepoOn(file);
998           }
999         }
1000
1001         CombinedProgressData subprogrcv(progress);
1002         
1003         // now delete it from cache
1004         cleanCache( todelete, subprogrcv);
1005
1006         MIL << todelete.alias() << " sucessfully deleted." << endl;
1007         return;
1008       } // else filepath is empty
1009
1010     }
1011     // should not be reached on a sucess workflow
1012     ZYPP_THROW(RepoNotFoundException(info));
1013   }
1014
1015   ////////////////////////////////////////////////////////////////////////////
1016
1017   void RepoManager::modifyRepository( const std::string &alias,
1018                                       const RepoInfo & newinfo,
1019                                       const ProgressData::ReceiverFnc & progressrcv )
1020   {
1021     RepoInfo toedit = getRepositoryInfo(alias);
1022
1023     if (toedit.filepath().empty())
1024     {
1025       ZYPP_THROW(RepoException("Can't figure where the repo is stored"));
1026     }
1027     else
1028     {
1029       // figure how many repos are there in the file:
1030       std::list<RepoInfo> filerepos = repositories_in_file(toedit.filepath());
1031
1032       // there are more repos in the same file
1033       // write them back except the deleted one.
1034       //TmpFile tmp;
1035       //std::ofstream file(tmp.path().c_str());
1036
1037       // assert the directory exists
1038       filesystem::assert_dir(toedit.filepath().dirname());
1039
1040       std::ofstream file(toedit.filepath().c_str());
1041       if (!file) {
1042         //ZYPP_THROW (Exception( "Can't open " + tmp.path().asString() ) );
1043         ZYPP_THROW (Exception( "Can't open " + toedit.filepath().asString() ) );
1044       }
1045       for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1046             fit != filerepos.end();
1047             ++fit )
1048       {
1049           // if the alias is different, dump the original
1050           // if it is the same, dump the provided one
1051           if ( (*fit).alias() != toedit.alias() )
1052             (*fit).dumpRepoOn(file);
1053           else
1054             newinfo.dumpRepoOn(file);
1055       }
1056     }
1057   }
1058
1059   ////////////////////////////////////////////////////////////////////////////
1060
1061   RepoInfo RepoManager::getRepositoryInfo( const std::string &alias,
1062                                            const ProgressData::ReceiverFnc & progressrcv )
1063   {
1064     std::list<RepoInfo> repos = knownRepositories();
1065     for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1066           it != repos.end();
1067           ++it )
1068     {
1069       if ( (*it).alias() == alias )
1070         return *it;
1071     }
1072     RepoInfo info;
1073     info.setAlias(info.alias());
1074     ZYPP_THROW(RepoNotFoundException(info));
1075   }
1076
1077   ////////////////////////////////////////////////////////////////////////////
1078
1079   RepoInfo RepoManager::getRepositoryInfo( const Url & url,
1080                                            const url::ViewOption & urlview,
1081                                            const ProgressData::ReceiverFnc & progressrcv )
1082   {
1083     std::list<RepoInfo> repos = knownRepositories();
1084     for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1085           it != repos.end();
1086           ++it )
1087     {
1088       for(RepoInfo::urls_const_iterator urlit = (*it).baseUrlsBegin();
1089           urlit != (*it).baseUrlsEnd();
1090           ++urlit)
1091       {
1092         if ((*urlit).asString(urlview) == url.asString(urlview))
1093           return *it;
1094       }
1095     }
1096     RepoInfo info;
1097     info.setAlias(info.alias());
1098     info.setBaseUrl(url);
1099     ZYPP_THROW(RepoNotFoundException(info));
1100   }
1101
1102   ////////////////////////////////////////////////////////////////////////////
1103
1104   std::ostream & operator<<( std::ostream & str, const RepoManager & obj )
1105   {
1106     return str << *obj._pimpl;
1107   }
1108
1109   /////////////////////////////////////////////////////////////////
1110 } // namespace zypp
1111 ///////////////////////////////////////////////////////////////////