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