1 /*---------------------------------------------------------------------\
3 | |__ / \ / / . \ . \ |
8 \---------------------------------------------------------------------*/
9 /** \file zypp/RepoManager.cc
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"
24 #include "zypp/repo/RepoException.h"
25 #include "zypp/RepoManager.h"
27 #include "zypp/cache/CacheStore.h"
28 #include "zypp/repo/cached/RepoImpl.h"
29 #include "zypp/media/MediaManager.h"
30 #include "zypp/MediaSetAccess.h"
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"
39 #include "zypp/ZYppCallbacks.h"
43 using namespace zypp::repo;
44 using namespace zypp::filesystem;
46 using namespace zypp::repo;
48 ///////////////////////////////////////////////////////////////////
50 { /////////////////////////////////////////////////////////////////
52 ///////////////////////////////////////////////////////////////////
54 // CLASS NAME : RepoManagerOptions
56 ///////////////////////////////////////////////////////////////////
58 RepoManagerOptions::RepoManagerOptions()
60 repoCachePath = ZConfig::instance().repoCachePath();
61 repoRawCachePath = ZConfig::instance().repoMetadataPath();
62 knownReposPath = ZConfig::instance().knownReposPath();
65 ////////////////////////////////////////////////////////////////////////////
68 * \short Simple callback to collect the results
70 * Classes like RepoFileParser call the callback
71 * once per each repo in a file.
73 * Passing this functor as callback, you can collect
74 * all resuls at the end, without dealing with async
89 bool collect( const RepoInfo &repo )
91 //MIL << "here in collector: " << repo.alias() << endl;
92 repos.push_back(repo);
93 //MIL << "added: " << repo.alias() << endl;
100 ////////////////////////////////////////////////////////////////////////////
103 * \short Internal version of clean cache
105 * Takes an extra CacheStore reference, so we avoid internally
106 * having 2 CacheStores writing to the same database.
108 static void cleanCacheInternal( cache::CacheStore &store,
109 const RepoInfo &info,
110 const ProgressData::ReceiverFnc & progressrcv = ProgressData::ReceiverFnc() )
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()));
117 if ( !store.isCached(info.alias()) )
120 MIL << info.alias() << " cleaning cache..." << endl;
121 data::RecordId id = store.lookupRepository(info.alias());
123 CombinedProgressData subprogrcv(progress);
125 store.cleanRepository(id, subprogrcv);
128 ////////////////////////////////////////////////////////////////////////////
131 * Reads RepoInfo's from a repo file.
133 * \param file pathname of the file to read.
135 static std::list<RepoInfo> repositories_in_file( const Pathname & file )
137 MIL << "repo file: " << file << endl;
138 RepoCollector collector;
139 parser::RepoFileReader parser( file, bind( &RepoCollector::collect, &collector, _1 ) );
140 return collector.repos;
143 ////////////////////////////////////////////////////////////////////////////
145 std::list<RepoInfo> readRepoFile(const Url & repo_file)
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)
150 Pathname path(url.getPathName());
151 url.setPathName ("/");
152 MediaSetAccess access(url);
153 Pathname local = access.provideFile(path);
155 DBG << "reading repo file " << repo_file << ", local path: " << local << endl;
157 return repositories_in_file(local);
160 ////////////////////////////////////////////////////////////////////////////
163 * \short List of RepoInfo's from a directory
165 * Goes trough every file ending with ".repo" in a directory and adds all
166 * RepoInfo's contained in that file.
168 * \param dir pathname of the directory to read.
170 static std::list<RepoInfo> repositories_in_dir( const Pathname &dir )
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"));
178 for ( list<Pathname>::const_iterator it = entries.begin(); it != entries.end(); ++it )
180 if (it->extension() == ".repo")
182 list<RepoInfo> tmp = repositories_in_file( *it );
183 repos.insert( repos.end(), tmp.begin(), tmp.end() );
185 //std::copy( collector.repos.begin(), collector.repos.end(), std::back_inserter(repos));
186 //MIL << "ok" << endl;
192 ////////////////////////////////////////////////////////////////////////////
194 static void assert_alias( const RepoInfo &info )
196 if (info.alias().empty())
197 ZYPP_THROW(RepoNoAliasException());
200 ////////////////////////////////////////////////////////////////////////////
202 static void assert_urls( const RepoInfo &info )
204 if (info.baseUrlsEmpty())
205 ZYPP_THROW(RepoNoUrlException());
208 ////////////////////////////////////////////////////////////////////////////
211 * \short Calculates the raw cache path for a repository
213 static Pathname rawcache_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info )
216 return opt.repoRawCachePath + info.alias();
219 ///////////////////////////////////////////////////////////////////
221 // CLASS NAME : RepoManager::Impl
223 ///////////////////////////////////////////////////////////////////
226 * \short RepoManager implementation.
228 struct RepoManager::Impl
230 Impl( const RepoManagerOptions &opt )
241 RepoManagerOptions options;
244 /** Offer default Impl. */
245 static shared_ptr<Impl> nullimpl()
247 static shared_ptr<Impl> _nullimpl( new Impl );
252 friend Impl * rwcowClone<Impl>( const Impl * rhs );
253 /** clone for RWCOW_pointer */
255 { return new Impl( *this ); }
257 ///////////////////////////////////////////////////////////////////
259 /** \relates RepoManager::Impl Stream output */
260 inline std::ostream & operator<<( std::ostream & str, const RepoManager::Impl & obj )
262 return str << "RepoManager::Impl";
265 ///////////////////////////////////////////////////////////////////
267 // CLASS NAME : RepoManager
269 ///////////////////////////////////////////////////////////////////
271 RepoManager::RepoManager( const RepoManagerOptions &opt )
272 : _pimpl( new Impl(opt) )
275 ////////////////////////////////////////////////////////////////////////////
277 RepoManager::~RepoManager()
280 ////////////////////////////////////////////////////////////////////////////
282 std::list<RepoInfo> RepoManager::knownRepositories() const
286 if ( PathInfo(_pimpl->options.knownReposPath).isExist() )
288 RepoInfoList repos = repositories_in_dir(_pimpl->options.knownReposPath);
289 for ( RepoInfoList::iterator it = repos.begin();
293 // set the metadata path for the repo
294 Pathname metadata_path = rawcache_path_for_repoinfo(_pimpl->options, (*it));
295 (*it).setMetadataPath(metadata_path);
300 return std::list<RepoInfo>();
305 ////////////////////////////////////////////////////////////////////////////
307 Pathname RepoManager::metadataPath( const RepoInfo &info ) const
309 return rawcache_path_for_repoinfo(_pimpl->options, info );
312 ////////////////////////////////////////////////////////////////////////////
314 RepoStatus RepoManager::metadataStatus( const RepoInfo &info ) const
316 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
317 RepoType repokind = info.type();
320 switch ( repokind.toEnum() )
322 case RepoType::NONE_e:
323 // unknown, probe the local metadata
324 repokind = probe(rawpath.asUrl());
330 switch ( repokind.toEnum() )
332 case RepoType::RPMMD_e :
334 status = RepoStatus( rawpath + "/repodata/repomd.xml");
338 case RepoType::YAST2_e :
340 // the order of RepoStatus && RepoStatus matters! (#304310)
341 status = RepoStatus( rawpath + "/content") && (RepoStatus( rawpath + "/media.1/media"));
345 case RepoType::RPMPLAINDIR_e :
347 if ( PathInfo(Pathname(rawpath + "/cookie")).isExist() )
348 status = RepoStatus( rawpath + "/cookie");
352 case RepoType::NONE_e :
353 // Return default RepoStatus in case of RepoType::NONE
354 // indicating it should be created?
355 // ZYPP_THROW(RepoUnknownTypeException());
361 void RepoManager::touchIndexFile(const RepoInfo & info)
363 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
365 RepoType repokind = info.type();
366 if ( repokind.toEnum() == RepoType::NONE_e )
367 // unknown, probe the local metadata
368 repokind = probe(rawpath.asUrl());
369 // if still unknown, just return
370 if (repokind == RepoType::NONE_e)
374 switch ( repokind.toEnum() )
376 case RepoType::RPMMD_e :
377 p = Pathname(rawpath + "/repodata/repomd.xml");
380 case RepoType::YAST2_e :
381 p = Pathname(rawpath + "/content");
384 case RepoType::RPMPLAINDIR_e :
385 p = Pathname(rawpath + "/cookie");
388 case RepoType::NONE_e :
393 // touch the file, ignore error (they are logged anyway)
394 filesystem::touch(p);
397 bool RepoManager::checkIfToRefreshMetadata( const RepoInfo &info,
399 RawMetadataRefreshPolicy policy )
403 RepoStatus oldstatus;
404 RepoStatus newstatus;
408 MIL << "Going to try to check whether refresh is needed for " << url << endl;
410 repo::RepoType repokind = info.type();
412 // if the type is unknown, try probing.
413 switch ( repokind.toEnum() )
415 case RepoType::NONE_e:
417 repokind = probe(url);
423 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
424 filesystem::assert_dir(rawpath);
425 oldstatus = metadataStatus(info);
427 // now we've got the old (cached) status, we can decide repo.refresh.delay
428 if (policy != RefreshForced)
430 // difference in seconds
431 double diff = difftime(
432 (Date::ValueType)Date::now(),
433 (Date::ValueType)oldstatus.timestamp()) / 60;
435 DBG << "oldstatus: " << (Date::ValueType)oldstatus.timestamp() << endl;
436 DBG << "current time: " << (Date::ValueType)Date::now() << endl;
437 DBG << "last refresh = " << diff << " minutes ago" << endl;
439 if (diff < ZConfig::instance().repo_refresh_delay())
441 MIL << "Repository '" << info.alias()
442 << "' has been refreshed less than repo.refresh.delay ("
443 << ZConfig::instance().repo_refresh_delay()
444 << ") minutes ago. Advising to skip refresh" << endl;
449 // create temp dir as sibling of rawpath
450 filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( rawpath ) );
452 if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
453 ( repokind.toEnum() == RepoType::YAST2_e ) )
455 MediaSetAccess media(url);
456 shared_ptr<repo::Downloader> downloader_ptr;
458 if ( repokind.toEnum() == RepoType::RPMMD_e )
459 downloader_ptr.reset(new yum::Downloader(info.path()));
461 downloader_ptr.reset( new susetags::Downloader(info.path()));
463 RepoStatus newstatus = downloader_ptr->status(media);
464 bool refresh = false;
465 if ( oldstatus.checksum() == newstatus.checksum() )
467 MIL << "repo has not changed" << endl;
468 if ( policy == RefreshForced )
470 MIL << "refresh set to forced" << endl;
476 MIL << "repo has changed, going to refresh" << endl;
481 touchIndexFile(info);
485 else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
487 RepoStatus newstatus = parser::plaindir::dirStatus(url.getPathName());
488 bool refresh = false;
489 if ( oldstatus.checksum() == newstatus.checksum() )
491 MIL << "repo has not changed" << endl;
492 if ( policy == RefreshForced )
494 MIL << "refresh set to forced" << endl;
500 MIL << "repo has changed, going to refresh" << endl;
505 touchIndexFile(info);
511 ZYPP_THROW(RepoUnknownTypeException());
514 catch ( const Exception &e )
517 ERR << "refresh check failed for " << url << endl;
521 return true; // default
524 void RepoManager::refreshMetadata( const RepoInfo &info,
525 RawMetadataRefreshPolicy policy,
526 const ProgressData::ReceiverFnc & progress )
531 // we will throw this later if no URL checks out fine
532 RepoException rexception(_("Valid metadata not found at specified URL(s)"));
534 // try urls one by one
535 for ( RepoInfo::urls_const_iterator it = info.baseUrlsBegin(); it != info.baseUrlsEnd(); ++it )
541 // check whether to refresh metadata
542 // if the check fails for this url, it throws, so another url will be checked
543 if (!checkIfToRefreshMetadata(info, url, policy))
546 MIL << "Going to refresh metadata from " << url << endl;
548 repo::RepoType repokind = info.type();
550 // if the type is unknown, try probing.
551 switch ( repokind.toEnum() )
553 case RepoType::NONE_e:
555 repokind = probe(*it);
561 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
562 filesystem::assert_dir(rawpath);
564 // create temp dir as sibling of rawpath
565 filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( rawpath ) );
567 if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
568 ( repokind.toEnum() == RepoType::YAST2_e ) )
570 MediaSetAccess media(url);
571 shared_ptr<repo::Downloader> downloader_ptr;
573 if ( repokind.toEnum() == RepoType::RPMMD_e )
574 downloader_ptr.reset(new yum::Downloader(info.path()));
576 downloader_ptr.reset( new susetags::Downloader(info.path()));
579 * Given a downloader, sets the other repos raw metadata
580 * path as cache paths for the fetcher, so if another
581 * repo has the same file, it will not download it
582 * but copy it from the other repository
584 std::list<RepoInfo> repos = knownRepositories();
585 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
589 downloader_ptr->addCachePath(rawcache_path_for_repoinfo( _pimpl->options, *it ));
592 downloader_ptr->download( media, tmpdir.path());
594 else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
596 RepoStatus newstatus = parser::plaindir::dirStatus(url.getPathName());
598 std::ofstream file(( tmpdir.path() + "/cookie").c_str());
600 ZYPP_THROW (Exception( "Can't open " + tmpdir.path().asString() + "/cookie" ) );
603 file << newstatus.checksum() << endl;
609 ZYPP_THROW(RepoUnknownTypeException());
612 // ok we have the metadata, now exchange
614 TmpDir oldmetadata( TmpDir::makeSibling( rawpath ) );
615 filesystem::rename( rawpath, oldmetadata.path() );
616 // move the just downloaded there
617 filesystem::rename( tmpdir.path(), rawpath );
621 catch ( const Exception &e )
624 ERR << "Trying another url..." << endl;
626 // remember the exception caught for the *first URL*
627 // if all other URLs fail, the rexception will be thrown with the
628 // cause of the problem of the first URL remembered
629 if (it == info.baseUrlsBegin())
630 rexception.remember(e);
633 ERR << "No more urls..." << endl;
634 ZYPP_THROW(rexception);
637 ////////////////////////////////////////////////////////////////////////////
639 void RepoManager::cleanMetadata( const RepoInfo &info,
640 const ProgressData::ReceiverFnc & progressfnc )
642 ProgressData progress(100);
643 progress.sendTo(progressfnc);
645 filesystem::recursive_rmdir(rawcache_path_for_repoinfo(_pimpl->options, info));
649 void RepoManager::buildCache( const RepoInfo &info,
650 CacheBuildPolicy policy,
651 const ProgressData::ReceiverFnc & progressrcv )
654 Pathname rawpath = rawcache_path_for_repoinfo(_pimpl->options, info);
656 cache::CacheStore store(_pimpl->options.repoCachePath);
658 RepoStatus raw_metadata_status = metadataStatus(info);
659 if ( raw_metadata_status.empty() )
661 ZYPP_THROW(RepoMetadataException(info));
664 bool needs_cleaning = false;
665 if ( store.isCached( info.alias() ) )
667 MIL << info.alias() << " is already cached." << endl;
668 data::RecordId id = store.lookupRepository(info.alias());
669 RepoStatus cache_status = store.repositoryStatus(id);
671 if ( cache_status.checksum() == raw_metadata_status.checksum() )
673 MIL << info.alias() << " cache is up to date with metadata." << endl;
674 if ( policy == BuildIfNeeded ) {
678 MIL << info.alias() << " cache rebuild is forced" << endl;
682 needs_cleaning = true;
685 ProgressData progress(100);
686 callback::SendReport<ProgressReport> report;
687 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
688 progress.name(str::form(_("Building repository '%s' cache"), info.name().c_str()));
692 cleanCacheInternal( store, info);
694 MIL << info.alias() << " building cache..." << endl;
695 data::RecordId id = store.lookupOrAppendRepository(info.alias());
697 repo::RepoType repokind = info.type();
699 // if the type is unknown, try probing.
700 switch ( repokind.toEnum() )
702 case RepoType::NONE_e:
703 // unknown, probe the local metadata
704 repokind = probe(rawpath.asUrl());
711 switch ( repokind.toEnum() )
713 case RepoType::RPMMD_e :
715 CombinedProgressData subprogrcv( progress, 100);
716 parser::yum::RepoParser parser(id, store, parser::yum::RepoParserOpts(), subprogrcv);
717 parser.parse(rawpath);
721 case RepoType::YAST2_e :
723 CombinedProgressData subprogrcv( progress, 100);
724 parser::susetags::RepoParser parser(id, store, subprogrcv);
725 parser.parse(rawpath);
729 case RepoType::RPMPLAINDIR_e :
731 CombinedProgressData subprogrcv( progress, 100);
732 InputStream is(rawpath + "cookie");
734 getline( is.stream(), buffer);
736 parser::plaindir::RepoParser parser(id, store, subprogrcv);
737 parser.parse(url.getPathName());
741 ZYPP_THROW(RepoUnknownTypeException());
744 // update timestamp and checksum
745 store.updateRepositoryStatus(id, raw_metadata_status);
747 MIL << "Commit cache.." << endl;
752 ////////////////////////////////////////////////////////////////////////////
754 repo::RepoType RepoManager::probe( const Url &url ) const
756 if ( url.getScheme() == "dir" && ! PathInfo( url.getPathName() ).isDir() )
758 // Handle non existing local directory in advance, as
759 // MediaSetAccess does not support it.
760 return repo::RepoType::NONE;
765 MediaSetAccess access(url);
766 if ( access.doesFileExist("/repodata/repomd.xml") )
767 return repo::RepoType::RPMMD;
768 if ( access.doesFileExist("/content") )
769 return repo::RepoType::YAST2;
771 // if it is a local url of type dir
772 if ( (! media::MediaManager::downloads(url)) && ( url.getScheme() == "dir" ) )
774 Pathname path = Pathname(url.getPathName());
775 if ( PathInfo(path).isDir() )
777 // allow empty dirs for now
778 return repo::RepoType::RPMPLAINDIR;
782 catch ( const media::MediaException &e )
785 RepoException enew("Error trying to read from " + url.asString());
789 catch ( const Exception &e )
792 Exception enew("Unknown error reading from " + url.asString());
797 return repo::RepoType::NONE;
800 ////////////////////////////////////////////////////////////////////////////
802 void RepoManager::cleanCache( const RepoInfo &info,
803 const ProgressData::ReceiverFnc & progressrcv )
805 cache::CacheStore store(_pimpl->options.repoCachePath);
806 cleanCacheInternal( store, info, progressrcv );
810 ////////////////////////////////////////////////////////////////////////////
812 bool RepoManager::isCached( const RepoInfo &info ) const
814 cache::CacheStore store(_pimpl->options.repoCachePath);
815 return store.isCached(info.alias());
818 RepoStatus RepoManager::cacheStatus( const RepoInfo &info ) const
820 cache::CacheStore store(_pimpl->options.repoCachePath);
821 data::RecordId id = store.lookupRepository(info.alias());
822 RepoStatus cache_status = store.repositoryStatus(id);
826 Repository RepoManager::createFromCache( const RepoInfo &info,
827 const ProgressData::ReceiverFnc & progressrcv )
829 callback::SendReport<ProgressReport> report;
830 ProgressData progress;
831 progress.sendTo(ProgressReportAdaptor( progressrcv, report ));
832 //progress.sendTo( progressrcv );
833 progress.name(str::form(_("Reading repository '%s' cache"), info.name().c_str()));
835 cache::CacheStore store(_pimpl->options.repoCachePath);
837 if ( ! store.isCached( info.alias() ) )
838 ZYPP_THROW(RepoNotCachedException());
840 MIL << "Repository " << info.alias() << " is cached" << endl;
842 data::RecordId id = store.lookupRepository(info.alias());
844 CombinedProgressData subprogrcv(progress);
846 repo::cached::RepoOptions opts( info, _pimpl->options.repoCachePath, id );
847 opts.readingResolvablesProgress = subprogrcv;
848 repo::cached::RepoImpl::Ptr repoimpl =
849 new repo::cached::RepoImpl( opts );
851 repoimpl->resolvables();
852 // read the resolvables from cache
853 return Repository(repoimpl);
856 ////////////////////////////////////////////////////////////////////////////
859 * Generate a non existing filename in a directory, using a base
860 * name. For example if a directory contains 3 files
866 * If you try to generate a unique filename for this directory,
867 * based on "ruu" you will get "ruu", but if you use the base
868 * "foo" you will get "foo_1"
870 * \param dir Directory where the file needs to be unique
871 * \param basefilename string to base the filename on.
873 static Pathname generate_non_existing_name( const Pathname &dir,
874 const std::string &basefilename )
876 string final_filename = basefilename;
878 while ( PathInfo(dir + final_filename).isExist() )
880 final_filename = basefilename + "_" + str::numstring(counter);
883 return dir + Pathname(final_filename);
886 ////////////////////////////////////////////////////////////////////////////
889 * \short Generate a related filename from a repo info
891 * From a repo info, it will try to use the alias as a filename
892 * escaping it if necessary. Other fallbacks can be added to
893 * this function in case there is no way to use the alias
895 static std::string generate_filename( const RepoInfo &info )
899 std::string filename = info.alias();
900 // replace slashes with underscores
901 size_t pos = filename.find(fnd);
902 while(pos!=string::npos)
904 filename.replace(pos,fnd.length(),rep);
905 pos = filename.find(fnd,pos+rep.length());
907 filename = Pathname(filename).extend(".repo").asString();
908 MIL << "generating filename for repo [" << info.alias() << "] : '" << filename << "'" << endl;
913 ////////////////////////////////////////////////////////////////////////////
915 void RepoManager::addRepository( const RepoInfo &info,
916 const ProgressData::ReceiverFnc & progressrcv )
920 ProgressData progress(100);
921 callback::SendReport<ProgressReport> report;
922 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
923 progress.name(str::form(_("Adding repository '%s'"), info.name().c_str()));
926 std::list<RepoInfo> repos = knownRepositories();
927 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
931 if ( info.alias() == (*it).alias() )
932 ZYPP_THROW(RepoAlreadyExistsException(info.alias()));
935 RepoInfo tosave = info;
937 // check the first url for now
938 if ( ZConfig::instance().repo_add_probe()
939 || ( tosave.type() == RepoType::NONE && tosave.enabled()) )
941 DBG << "unknown repository type, probing" << endl;
944 probedtype = probe(*tosave.baseUrlsBegin());
945 if ( tosave.baseUrlsSize() > 0 )
947 if ( probedtype == RepoType::NONE )
948 ZYPP_THROW(RepoUnknownTypeException());
950 tosave.setType(probedtype);
956 // assert the directory exists
957 filesystem::assert_dir(_pimpl->options.knownReposPath);
959 Pathname repofile = generate_non_existing_name(_pimpl->options.knownReposPath,
960 generate_filename(tosave));
961 // now we have a filename that does not exists
962 MIL << "Saving repo in " << repofile << endl;
964 std::ofstream file(repofile.c_str());
966 ZYPP_THROW (Exception( "Can't open " + repofile.asString() ) );
969 tosave.dumpRepoOn(file);
971 MIL << "done" << endl;
974 void RepoManager::addRepositories( const Url &url,
975 const ProgressData::ReceiverFnc & progressrcv )
977 std::list<RepoInfo> knownrepos = knownRepositories();
978 std::list<RepoInfo> repos = readRepoFile(url);
979 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
983 // look if the alias is in the known repos.
984 for ( std::list<RepoInfo>::const_iterator kit = knownrepos.begin();
985 kit != knownrepos.end();
988 if ( (*it).alias() == (*kit).alias() )
990 ERR << "To be added repo " << (*it).alias() << " conflicts with existing repo " << (*kit).alias() << endl;
991 ZYPP_THROW(RepoAlreadyExistsException((*it).alias()));
996 string filename = Pathname(url.getPathName()).basename();
998 if ( filename == Pathname() )
999 ZYPP_THROW(RepoException("Invalid repo file name at " + url.asString() ));
1001 // assert the directory exists
1002 filesystem::assert_dir(_pimpl->options.knownReposPath);
1004 Pathname repofile = generate_non_existing_name(_pimpl->options.knownReposPath, filename);
1005 // now we have a filename that does not exists
1006 MIL << "Saving " << repos.size() << " repo" << ( repos.size() ? "s" : "" ) << " in " << repofile << endl;
1008 std::ofstream file(repofile.c_str());
1010 ZYPP_THROW (Exception( "Can't open " + repofile.asString() ) );
1013 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1017 MIL << "Saving " << (*it).alias() << endl;
1018 (*it).dumpRepoOn(file);
1020 MIL << "done" << endl;
1023 ////////////////////////////////////////////////////////////////////////////
1025 void RepoManager::removeRepository( const RepoInfo & info,
1026 const ProgressData::ReceiverFnc & progressrcv)
1028 ProgressData progress;
1029 callback::SendReport<ProgressReport> report;
1030 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1031 progress.name(str::form(_("Removing repository '%s'"), info.name().c_str()));
1033 MIL << "Going to delete repo " << info.alias() << endl;
1035 std::list<RepoInfo> repos = knownRepositories();
1036 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1040 // they can be the same only if the provided is empty, that means
1041 // the provided repo has no alias
1043 if ( (!info.alias().empty()) && ( info.alias() != (*it).alias() ) )
1046 // TODO match by url
1048 // we have a matcing repository, now we need to know
1049 // where it does come from.
1050 RepoInfo todelete = *it;
1051 if (todelete.filepath().empty())
1053 ZYPP_THROW(RepoException("Can't figure where the repo is stored"));
1057 // figure how many repos are there in the file:
1058 std::list<RepoInfo> filerepos = repositories_in_file(todelete.filepath());
1059 if ( (filerepos.size() == 1) && ( filerepos.front().alias() == todelete.alias() ) )
1061 // easy, only this one, just delete the file
1062 if ( filesystem::unlink(todelete.filepath()) != 0 )
1064 ZYPP_THROW(RepoException("Can't delete " + todelete.filepath().asString()));
1066 MIL << todelete.alias() << " sucessfully deleted." << endl;
1070 // there are more repos in the same file
1071 // write them back except the deleted one.
1073 //std::ofstream file(tmp.path().c_str());
1075 // assert the directory exists
1076 filesystem::assert_dir(todelete.filepath().dirname());
1078 std::ofstream file(todelete.filepath().c_str());
1080 //ZYPP_THROW (Exception( "Can't open " + tmp.path().asString() ) );
1081 ZYPP_THROW (Exception( "Can't open " + todelete.filepath().asString() ) );
1083 for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1084 fit != filerepos.end();
1087 if ( (*fit).alias() != todelete.alias() )
1088 (*fit).dumpRepoOn(file);
1092 CombinedProgressData subprogrcv(progress, 70);
1093 CombinedProgressData cleansubprogrcv(progress, 30);
1094 // now delete it from cache
1095 cleanCache( todelete, subprogrcv);
1096 // now delete metadata (#301037)
1097 cleanMetadata( todelete, cleansubprogrcv);
1098 MIL << todelete.alias() << " sucessfully deleted." << endl;
1100 } // else filepath is empty
1103 // should not be reached on a sucess workflow
1104 ZYPP_THROW(RepoNotFoundException(info));
1107 ////////////////////////////////////////////////////////////////////////////
1109 void RepoManager::modifyRepository( const std::string &alias,
1110 const RepoInfo & newinfo,
1111 const ProgressData::ReceiverFnc & progressrcv )
1113 RepoInfo toedit = getRepositoryInfo(alias);
1115 if (toedit.filepath().empty())
1117 ZYPP_THROW(RepoException("Can't figure where the repo is stored"));
1121 // figure how many repos are there in the file:
1122 std::list<RepoInfo> filerepos = repositories_in_file(toedit.filepath());
1124 // there are more repos in the same file
1125 // write them back except the deleted one.
1127 //std::ofstream file(tmp.path().c_str());
1129 // assert the directory exists
1130 filesystem::assert_dir(toedit.filepath().dirname());
1132 std::ofstream file(toedit.filepath().c_str());
1134 //ZYPP_THROW (Exception( "Can't open " + tmp.path().asString() ) );
1135 ZYPP_THROW (Exception( "Can't open " + toedit.filepath().asString() ) );
1137 for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1138 fit != filerepos.end();
1141 // if the alias is different, dump the original
1142 // if it is the same, dump the provided one
1143 if ( (*fit).alias() != toedit.alias() )
1144 (*fit).dumpRepoOn(file);
1146 newinfo.dumpRepoOn(file);
1151 ////////////////////////////////////////////////////////////////////////////
1153 RepoInfo RepoManager::getRepositoryInfo( const std::string &alias,
1154 const ProgressData::ReceiverFnc & progressrcv )
1156 std::list<RepoInfo> repos = knownRepositories();
1157 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1161 if ( (*it).alias() == alias )
1165 info.setAlias(info.alias());
1166 ZYPP_THROW(RepoNotFoundException(info));
1169 ////////////////////////////////////////////////////////////////////////////
1171 RepoInfo RepoManager::getRepositoryInfo( const Url & url,
1172 const url::ViewOption & urlview,
1173 const ProgressData::ReceiverFnc & progressrcv )
1175 std::list<RepoInfo> repos = knownRepositories();
1176 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1180 for(RepoInfo::urls_const_iterator urlit = (*it).baseUrlsBegin();
1181 urlit != (*it).baseUrlsEnd();
1184 if ((*urlit).asString(urlview) == url.asString(urlview))
1189 info.setAlias(info.alias());
1190 info.setBaseUrl(url);
1191 ZYPP_THROW(RepoNotFoundException(info));
1194 ////////////////////////////////////////////////////////////////////////////
1196 std::ostream & operator<<( std::ostream & str, const RepoManager & obj )
1198 return str << *obj._pimpl;
1201 /////////////////////////////////////////////////////////////////
1203 ///////////////////////////////////////////////////////////////////