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 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 list<RepoInfo> tmp = repositories_in_file( *it );
181 repos.insert( repos.end(), tmp.begin(), tmp.end() );
183 //std::copy( collector.repos.begin(), collector.repos.end(), std::back_inserter(repos));
184 //MIL << "ok" << endl;
189 ////////////////////////////////////////////////////////////////////////////
191 static void assert_alias( const RepoInfo &info )
193 if (info.alias().empty())
194 ZYPP_THROW(RepoNoAliasException());
197 ////////////////////////////////////////////////////////////////////////////
199 static void assert_urls( const RepoInfo &info )
201 if (info.baseUrlsEmpty())
202 ZYPP_THROW(RepoNoUrlException());
205 ////////////////////////////////////////////////////////////////////////////
208 * \short Calculates the raw cache path for a repository
210 static Pathname rawcache_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info )
213 return opt.repoRawCachePath + info.alias();
216 ///////////////////////////////////////////////////////////////////
218 // CLASS NAME : RepoManager::Impl
220 ///////////////////////////////////////////////////////////////////
223 * \short RepoManager implementation.
225 struct RepoManager::Impl
227 Impl( const RepoManagerOptions &opt )
238 RepoManagerOptions options;
241 /** Offer default Impl. */
242 static shared_ptr<Impl> nullimpl()
244 static shared_ptr<Impl> _nullimpl( new Impl );
249 friend Impl * rwcowClone<Impl>( const Impl * rhs );
250 /** clone for RWCOW_pointer */
252 { return new Impl( *this ); }
254 ///////////////////////////////////////////////////////////////////
256 /** \relates RepoManager::Impl Stream output */
257 inline std::ostream & operator<<( std::ostream & str, const RepoManager::Impl & obj )
259 return str << "RepoManager::Impl";
262 ///////////////////////////////////////////////////////////////////
264 // CLASS NAME : RepoManager
266 ///////////////////////////////////////////////////////////////////
268 RepoManager::RepoManager( const RepoManagerOptions &opt )
269 : _pimpl( new Impl(opt) )
272 ////////////////////////////////////////////////////////////////////////////
274 RepoManager::~RepoManager()
277 ////////////////////////////////////////////////////////////////////////////
279 std::list<RepoInfo> RepoManager::knownRepositories() const
283 if ( PathInfo(_pimpl->options.knownReposPath).isExist() )
285 RepoInfoList repos = repositories_in_dir(_pimpl->options.knownReposPath);
286 for ( RepoInfoList::iterator it = repos.begin();
290 // set the metadata path for the repo
291 Pathname metadata_path = rawcache_path_for_repoinfo(_pimpl->options, (*it));
292 (*it).setMetadataPath(metadata_path);
297 return std::list<RepoInfo>();
302 ////////////////////////////////////////////////////////////////////////////
304 RepoStatus RepoManager::metadataStatus( const RepoInfo &info ) const
306 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
307 RepoType repokind = info.type();
310 switch ( repokind.toEnum() )
312 case RepoType::NONE_e:
313 // unknown, probe the local metadata
314 repokind = probe(rawpath.asUrl());
320 switch ( repokind.toEnum() )
322 case RepoType::RPMMD_e :
324 status = RepoStatus( rawpath + "/repodata/repomd.xml");
328 case RepoType::YAST2_e :
330 status = RepoStatus( rawpath + "/content");
334 case RepoType::RPMPLAINDIR_e :
336 if ( PathInfo(Pathname(rawpath + "/cookie")).isExist() )
337 status = RepoStatus( rawpath + "/cookie");
341 case RepoType::NONE_e :
342 // Return default RepoStatus in case of RepoType::NONE
343 // indicating it should be created?
344 // ZYPP_THROW(RepoUnknownTypeException());
350 void RepoManager::touchIndexFile(const RepoInfo & info)
352 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
354 RepoType repokind = info.type();
355 if ( repokind.toEnum() == RepoType::NONE_e )
356 // unknown, probe the local metadata
357 repokind = probe(rawpath.asUrl());
358 // if still unknown, just return
359 if (repokind == RepoType::NONE_e)
363 switch ( repokind.toEnum() )
365 case RepoType::RPMMD_e :
366 p = Pathname(rawpath + "/repodata/repomd.xml");
369 case RepoType::YAST2_e :
370 p = Pathname(rawpath + "/content");
373 case RepoType::RPMPLAINDIR_e :
374 p = Pathname(rawpath + "/cookie");
377 case RepoType::NONE_e :
382 // touch the file, ignore error (they are logged anyway)
383 filesystem::touch(p);
386 bool RepoManager::checkIfToRefreshMetadata( const RepoInfo &info,
388 RawMetadataRefreshPolicy policy )
392 RepoStatus oldstatus;
393 RepoStatus newstatus;
397 MIL << "Going to try to check whether refresh is needed for " << url << endl;
399 repo::RepoType repokind = info.type();
401 // if the type is unknown, try probing.
402 switch ( repokind.toEnum() )
404 case RepoType::NONE_e:
406 repokind = probe(url);
412 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
413 filesystem::assert_dir(rawpath);
414 oldstatus = metadataStatus(info);
416 // now we've got the old (cached) status, we can decide repo.refresh.delay
417 if (policy != RefreshForced)
419 // difference in seconds
420 double diff = difftime(
421 (Date::ValueType)Date::now(),
422 (Date::ValueType)oldstatus.timestamp()) / 60;
424 DBG << "oldstatus: " << (Date::ValueType)oldstatus.timestamp() << endl;
425 DBG << "current time: " << (Date::ValueType)Date::now() << endl;
426 DBG << "last refresh = " << diff << " minutes ago" << endl;
428 if (diff < ZConfig::instance().repo_refresh_delay())
430 MIL << "Repository '" << info.alias()
431 << "' has been refreshed less than repo.refresh.delay ("
432 << ZConfig::instance().repo_refresh_delay()
433 << ") minutes ago. Advising to skip refresh" << endl;
438 // create temp dir as sibling of rawpath
439 filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( rawpath ) );
441 if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
442 ( repokind.toEnum() == RepoType::YAST2_e ) )
444 MediaSetAccess media(url);
445 shared_ptr<repo::Downloader> downloader_ptr;
447 if ( repokind.toEnum() == RepoType::RPMMD_e )
448 downloader_ptr.reset(new yum::Downloader(info.path()));
450 downloader_ptr.reset( new susetags::Downloader(info.path()));
452 RepoStatus newstatus = downloader_ptr->status(media);
453 bool refresh = false;
454 if ( oldstatus.checksum() == newstatus.checksum() )
456 MIL << "repo has not changed" << endl;
457 if ( policy == RefreshForced )
459 MIL << "refresh set to forced" << endl;
465 MIL << "repo has changed, going to refresh" << endl;
470 touchIndexFile(info);
474 else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
476 RepoStatus newstatus = parser::plaindir::dirStatus(url.getPathName());
477 bool refresh = false;
478 if ( oldstatus.checksum() == newstatus.checksum() )
480 MIL << "repo has not changed" << endl;
481 if ( policy == RefreshForced )
483 MIL << "refresh set to forced" << endl;
489 MIL << "repo has changed, going to refresh" << endl;
494 touchIndexFile(info);
500 ZYPP_THROW(RepoUnknownTypeException());
503 catch ( const Exception &e )
506 ERR << "refresh check failed for " << url << endl;
510 return true; // default
513 void RepoManager::refreshMetadata( const RepoInfo &info,
514 RawMetadataRefreshPolicy policy,
515 const ProgressData::ReceiverFnc & progress )
520 // try urls one by one
521 for ( RepoInfo::urls_const_iterator it = info.baseUrlsBegin(); it != info.baseUrlsEnd(); ++it )
527 // check whether to refresh metadata
528 // if the check fails for this url, it throws, so another url will be checked
529 if (!checkIfToRefreshMetadata(info, url, policy))
532 MIL << "Going to refresh metadata from " << url << endl;
534 repo::RepoType repokind = info.type();
536 // if the type is unknown, try probing.
537 switch ( repokind.toEnum() )
539 case RepoType::NONE_e:
541 repokind = probe(*it);
547 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
548 filesystem::assert_dir(rawpath);
550 // create temp dir as sibling of rawpath
551 filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( rawpath ) );
553 if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
554 ( repokind.toEnum() == RepoType::YAST2_e ) )
556 MediaSetAccess media(url);
557 shared_ptr<repo::Downloader> downloader_ptr;
559 if ( repokind.toEnum() == RepoType::RPMMD_e )
560 downloader_ptr.reset(new yum::Downloader(info.path()));
562 downloader_ptr.reset( new susetags::Downloader(info.path()));
565 * Given a downloader, sets the other repos raw metadata
566 * path as cache paths for the fetcher, so if another
567 * repo has the same file, it will not download it
568 * but copy it from the other repository
570 std::list<RepoInfo> repos = knownRepositories();
571 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
575 downloader_ptr->addCachePath(rawcache_path_for_repoinfo( _pimpl->options, *it ));
578 downloader_ptr->download( media, tmpdir.path());
580 else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
582 RepoStatus newstatus = parser::plaindir::dirStatus(url.getPathName());
584 std::ofstream file(( tmpdir.path() + "/cookie").c_str());
586 ZYPP_THROW (Exception( "Can't open " + tmpdir.path().asString() + "/cookie" ) );
589 file << newstatus.checksum() << endl;
595 ZYPP_THROW(RepoUnknownTypeException());
598 // ok we have the metadata, now exchange
600 TmpDir oldmetadata( TmpDir::makeSibling( rawpath ) );
601 filesystem::rename( rawpath, oldmetadata.path() );
602 // move the just downloaded there
603 filesystem::rename( tmpdir.path(), rawpath );
607 catch ( const Exception &e )
610 ERR << "Trying another url..." << endl;
613 ERR << "No more urls..." << endl;
614 ZYPP_THROW(RepoException(_("Valid metadata not found at specified URL(s)")));
617 ////////////////////////////////////////////////////////////////////////////
619 void RepoManager::cleanMetadata( const RepoInfo &info,
620 const ProgressData::ReceiverFnc & progress )
622 filesystem::recursive_rmdir(rawcache_path_for_repoinfo(_pimpl->options, info));
625 void RepoManager::buildCache( const RepoInfo &info,
626 CacheBuildPolicy policy,
627 const ProgressData::ReceiverFnc & progressrcv )
630 Pathname rawpath = rawcache_path_for_repoinfo(_pimpl->options, info);
632 cache::CacheStore store(_pimpl->options.repoCachePath);
634 RepoStatus raw_metadata_status = metadataStatus(info);
635 if ( raw_metadata_status.empty() )
637 ZYPP_THROW(RepoMetadataException(info));
640 bool needs_cleaning = false;
641 if ( store.isCached( info.alias() ) )
643 MIL << info.alias() << " is already cached." << endl;
644 data::RecordId id = store.lookupRepository(info.alias());
645 RepoStatus cache_status = store.repositoryStatus(id);
647 if ( cache_status.checksum() == raw_metadata_status.checksum() )
649 MIL << info.alias() << " cache is up to date with metadata." << endl;
650 if ( policy == BuildIfNeeded ) {
654 MIL << info.alias() << " cache rebuild is forced" << endl;
658 needs_cleaning = true;
661 ProgressData progress(100);
662 callback::SendReport<ProgressReport> report;
663 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
664 progress.name(str::form(_("Building repository '%s' cache"), info.name().c_str()));
668 cleanCacheInternal( store, info);
670 MIL << info.alias() << " building cache..." << endl;
671 data::RecordId id = store.lookupOrAppendRepository(info.alias());
673 repo::RepoType repokind = info.type();
675 // if the type is unknown, try probing.
676 switch ( repokind.toEnum() )
678 case RepoType::NONE_e:
679 // unknown, probe the local metadata
680 repokind = probe(rawpath.asUrl());
687 switch ( repokind.toEnum() )
689 case RepoType::RPMMD_e :
691 CombinedProgressData subprogrcv( progress, 100);
692 parser::yum::RepoParser parser(id, store, parser::yum::RepoParserOpts(), subprogrcv);
693 parser.parse(rawpath);
697 case RepoType::YAST2_e :
699 CombinedProgressData subprogrcv( progress, 100);
700 parser::susetags::RepoParser parser(id, store, subprogrcv);
701 parser.parse(rawpath);
705 case RepoType::RPMPLAINDIR_e :
707 CombinedProgressData subprogrcv( progress, 100);
708 InputStream is(rawpath + "cookie");
710 getline( is.stream(), buffer);
712 parser::plaindir::RepoParser parser(id, store, subprogrcv);
713 parser.parse(url.getPathName());
717 ZYPP_THROW(RepoUnknownTypeException());
720 // update timestamp and checksum
721 store.updateRepositoryStatus(id, raw_metadata_status);
723 MIL << "Commit cache.." << endl;
728 ////////////////////////////////////////////////////////////////////////////
730 repo::RepoType RepoManager::probe( const Url &url ) const
732 if ( url.getScheme() == "dir" && ! PathInfo( url.getPathName() ).isDir() )
734 // Handle non existing local directory in advance, as
735 // MediaSetAccess does not support it.
736 return repo::RepoType::NONE;
741 MediaSetAccess access(url);
742 if ( access.doesFileExist("/repodata/repomd.xml") )
743 return repo::RepoType::RPMMD;
744 if ( access.doesFileExist("/content") )
745 return repo::RepoType::YAST2;
747 // if it is a local url of type dir
748 if ( (! media::MediaManager::downloads(url)) && ( url.getScheme() == "dir" ) )
750 Pathname path = Pathname(url.getPathName());
751 if ( PathInfo(path).isDir() )
753 // allow empty dirs for now
754 return repo::RepoType::RPMPLAINDIR;
758 catch ( const media::MediaException &e )
761 RepoException enew("Error trying to read from " + url.asString());
765 catch ( const Exception &e )
768 Exception enew("Unknown error reading from " + url.asString());
773 return repo::RepoType::NONE;
776 ////////////////////////////////////////////////////////////////////////////
778 void RepoManager::cleanCache( const RepoInfo &info,
779 const ProgressData::ReceiverFnc & progressrcv )
781 cache::CacheStore store(_pimpl->options.repoCachePath);
782 cleanCacheInternal( store, info, progressrcv );
786 ////////////////////////////////////////////////////////////////////////////
788 bool RepoManager::isCached( const RepoInfo &info ) const
790 cache::CacheStore store(_pimpl->options.repoCachePath);
791 return store.isCached(info.alias());
794 RepoStatus RepoManager::cacheStatus( const RepoInfo &info ) const
796 cache::CacheStore store(_pimpl->options.repoCachePath);
797 data::RecordId id = store.lookupRepository(info.alias());
798 RepoStatus cache_status = store.repositoryStatus(id);
802 Repository RepoManager::createFromCache( const RepoInfo &info,
803 const ProgressData::ReceiverFnc & progressrcv )
805 callback::SendReport<ProgressReport> report;
806 ProgressData progress;
807 progress.sendTo(ProgressReportAdaptor( progressrcv, report ));
808 //progress.sendTo( progressrcv );
809 progress.name(str::form(_("Reading repository '%s' cache"), info.name().c_str()));
811 cache::CacheStore store(_pimpl->options.repoCachePath);
813 if ( ! store.isCached( info.alias() ) )
814 ZYPP_THROW(RepoNotCachedException());
816 MIL << "Repository " << info.alias() << " is cached" << endl;
818 data::RecordId id = store.lookupRepository(info.alias());
820 CombinedProgressData subprogrcv(progress);
822 repo::cached::RepoOptions opts( info, _pimpl->options.repoCachePath, id );
823 opts.readingResolvablesProgress = subprogrcv;
824 repo::cached::RepoImpl::Ptr repoimpl =
825 new repo::cached::RepoImpl( opts );
827 repoimpl->resolvables();
828 // read the resolvables from cache
829 return Repository(repoimpl);
832 ////////////////////////////////////////////////////////////////////////////
835 * Generate a non existing filename in a directory, using a base
836 * name. For example if a directory contains 3 files
842 * If you try to generate a unique filename for this directory,
843 * based on "ruu" you will get "ruu", but if you use the base
844 * "foo" you will get "foo_1"
846 * \param dir Directory where the file needs to be unique
847 * \param basefilename string to base the filename on.
849 static Pathname generate_non_existing_name( const Pathname &dir,
850 const std::string &basefilename )
852 string final_filename = basefilename;
854 while ( PathInfo(dir + final_filename).isExist() )
856 final_filename = basefilename + "_" + str::numstring(counter);
859 return dir + Pathname(final_filename);
862 ////////////////////////////////////////////////////////////////////////////
865 * \short Generate a related filename from a repo info
867 * From a repo info, it will try to use the alias as a filename
868 * escaping it if necessary. Other fallbacks can be added to
869 * this function in case there is no way to use the alias
871 static std::string generate_filename( const RepoInfo &info )
875 std::string filename = info.alias();
876 // replace slashes with underscores
877 size_t pos = filename.find(fnd);
878 while(pos!=string::npos)
880 filename.replace(pos,fnd.length(),rep);
881 pos = filename.find(fnd,pos+rep.length());
883 filename = Pathname(filename).extend(".repo").asString();
884 MIL << "generating filename for repo [" << info.alias() << "] : '" << filename << "'" << endl;
889 ////////////////////////////////////////////////////////////////////////////
891 void RepoManager::addRepository( const RepoInfo &info,
892 const ProgressData::ReceiverFnc & progressrcv )
896 ProgressData progress(100);
897 callback::SendReport<ProgressReport> report;
898 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
899 progress.name(str::form(_("Adding repository '%s'"), info.name().c_str()));
902 std::list<RepoInfo> repos = knownRepositories();
903 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
907 if ( info.alias() == (*it).alias() )
908 ZYPP_THROW(RepoAlreadyExistsException(info.alias()));
911 RepoInfo tosave = info;
913 // check the first url for now
914 if ( ZConfig::instance().repo_add_probe() || ( tosave.type() == RepoType::NONE ) )
917 probedtype = probe(*tosave.baseUrlsBegin());
918 if ( tosave.baseUrlsSize() > 0 )
920 if ( probedtype == RepoType::NONE )
921 ZYPP_THROW(RepoUnknownTypeException());
923 tosave.setType(probedtype);
929 // assert the directory exists
930 filesystem::assert_dir(_pimpl->options.knownReposPath);
932 Pathname repofile = generate_non_existing_name(_pimpl->options.knownReposPath,
933 generate_filename(tosave));
934 // now we have a filename that does not exists
935 MIL << "Saving repo in " << repofile << endl;
937 std::ofstream file(repofile.c_str());
939 ZYPP_THROW (Exception( "Can't open " + repofile.asString() ) );
942 tosave.dumpRepoOn(file);
944 MIL << "done" << endl;
947 void RepoManager::addRepositories( const Url &url,
948 const ProgressData::ReceiverFnc & progressrcv )
950 std::list<RepoInfo> knownrepos = knownRepositories();
951 std::list<RepoInfo> repos = readRepoFile(url);
952 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
956 // look if the alias is in the known repos.
957 for ( std::list<RepoInfo>::const_iterator kit = knownrepos.begin();
958 kit != knownrepos.end();
961 if ( (*it).alias() == (*kit).alias() )
963 ERR << "To be added repo " << (*it).alias() << " conflicts with existing repo " << (*kit).alias() << endl;
964 ZYPP_THROW(RepoAlreadyExistsException((*it).alias()));
969 string filename = Pathname(url.getPathName()).basename();
971 if ( filename == Pathname() )
972 ZYPP_THROW(RepoException("Invalid repo file name at " + url.asString() ));
974 // assert the directory exists
975 filesystem::assert_dir(_pimpl->options.knownReposPath);
977 Pathname repofile = generate_non_existing_name(_pimpl->options.knownReposPath, filename);
978 // now we have a filename that does not exists
979 MIL << "Saving " << repos.size() << " repo" << ( repos.size() ? "s" : "" ) << " in " << repofile << endl;
981 std::ofstream file(repofile.c_str());
983 ZYPP_THROW (Exception( "Can't open " + repofile.asString() ) );
986 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
990 MIL << "Saving " << (*it).alias() << endl;
991 (*it).dumpRepoOn(file);
993 MIL << "done" << endl;
996 ////////////////////////////////////////////////////////////////////////////
998 void RepoManager::removeRepository( const RepoInfo & info,
999 const ProgressData::ReceiverFnc & progressrcv)
1001 ProgressData progress;
1002 callback::SendReport<ProgressReport> report;
1003 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1004 progress.name(str::form(_("Removing repository '%s'"), info.name().c_str()));
1006 MIL << "Going to delete repo " << info.alias() << endl;
1008 std::list<RepoInfo> repos = knownRepositories();
1009 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1013 // they can be the same only if the provided is empty, that means
1014 // the provided repo has no alias
1016 if ( (!info.alias().empty()) && ( info.alias() != (*it).alias() ) )
1019 // TODO match by url
1021 // we have a matcing repository, now we need to know
1022 // where it does come from.
1023 RepoInfo todelete = *it;
1024 if (todelete.filepath().empty())
1026 ZYPP_THROW(RepoException("Can't figure where the repo is stored"));
1030 // figure how many repos are there in the file:
1031 std::list<RepoInfo> filerepos = repositories_in_file(todelete.filepath());
1032 if ( (filerepos.size() == 1) && ( filerepos.front().alias() == todelete.alias() ) )
1034 // easy, only this one, just delete the file
1035 if ( filesystem::unlink(todelete.filepath()) != 0 )
1037 ZYPP_THROW(RepoException("Can't delete " + todelete.filepath().asString()));
1039 MIL << todelete.alias() << " sucessfully deleted." << endl;
1043 // there are more repos in the same file
1044 // write them back except the deleted one.
1046 //std::ofstream file(tmp.path().c_str());
1048 // assert the directory exists
1049 filesystem::assert_dir(todelete.filepath().dirname());
1051 std::ofstream file(todelete.filepath().c_str());
1053 //ZYPP_THROW (Exception( "Can't open " + tmp.path().asString() ) );
1054 ZYPP_THROW (Exception( "Can't open " + todelete.filepath().asString() ) );
1056 for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1057 fit != filerepos.end();
1060 if ( (*fit).alias() != todelete.alias() )
1061 (*fit).dumpRepoOn(file);
1065 CombinedProgressData subprogrcv(progress);
1067 // now delete it from cache
1068 cleanCache( todelete, subprogrcv);
1070 MIL << todelete.alias() << " sucessfully deleted." << endl;
1072 } // else filepath is empty
1075 // should not be reached on a sucess workflow
1076 ZYPP_THROW(RepoNotFoundException(info));
1079 ////////////////////////////////////////////////////////////////////////////
1081 void RepoManager::modifyRepository( const std::string &alias,
1082 const RepoInfo & newinfo,
1083 const ProgressData::ReceiverFnc & progressrcv )
1085 RepoInfo toedit = getRepositoryInfo(alias);
1087 if (toedit.filepath().empty())
1089 ZYPP_THROW(RepoException("Can't figure where the repo is stored"));
1093 // figure how many repos are there in the file:
1094 std::list<RepoInfo> filerepos = repositories_in_file(toedit.filepath());
1096 // there are more repos in the same file
1097 // write them back except the deleted one.
1099 //std::ofstream file(tmp.path().c_str());
1101 // assert the directory exists
1102 filesystem::assert_dir(toedit.filepath().dirname());
1104 std::ofstream file(toedit.filepath().c_str());
1106 //ZYPP_THROW (Exception( "Can't open " + tmp.path().asString() ) );
1107 ZYPP_THROW (Exception( "Can't open " + toedit.filepath().asString() ) );
1109 for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1110 fit != filerepos.end();
1113 // if the alias is different, dump the original
1114 // if it is the same, dump the provided one
1115 if ( (*fit).alias() != toedit.alias() )
1116 (*fit).dumpRepoOn(file);
1118 newinfo.dumpRepoOn(file);
1123 ////////////////////////////////////////////////////////////////////////////
1125 RepoInfo RepoManager::getRepositoryInfo( const std::string &alias,
1126 const ProgressData::ReceiverFnc & progressrcv )
1128 std::list<RepoInfo> repos = knownRepositories();
1129 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1133 if ( (*it).alias() == alias )
1137 info.setAlias(info.alias());
1138 ZYPP_THROW(RepoNotFoundException(info));
1141 ////////////////////////////////////////////////////////////////////////////
1143 RepoInfo RepoManager::getRepositoryInfo( const Url & url,
1144 const url::ViewOption & urlview,
1145 const ProgressData::ReceiverFnc & progressrcv )
1147 std::list<RepoInfo> repos = knownRepositories();
1148 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1152 for(RepoInfo::urls_const_iterator urlit = (*it).baseUrlsBegin();
1153 urlit != (*it).baseUrlsEnd();
1156 if ((*urlit).asString(urlview) == url.asString(urlview))
1161 info.setAlias(info.alias());
1162 info.setBaseUrl(url);
1163 ZYPP_THROW(RepoNotFoundException(info));
1166 ////////////////////////////////////////////////////////////////////////////
1168 std::ostream & operator<<( std::ostream & str, const RepoManager & obj )
1170 return str << *obj._pimpl;
1173 /////////////////////////////////////////////////////////////////
1175 ///////////////////////////////////////////////////////////////////