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 Pathname RepoManager::metadataPath( const RepoInfo &info ) const
306 return rawcache_path_for_repoinfo(_pimpl->options, info );
309 ////////////////////////////////////////////////////////////////////////////
311 RepoStatus RepoManager::metadataStatus( const RepoInfo &info ) const
313 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
314 RepoType repokind = info.type();
317 switch ( repokind.toEnum() )
319 case RepoType::NONE_e:
320 // unknown, probe the local metadata
321 repokind = probe(rawpath.asUrl());
327 switch ( repokind.toEnum() )
329 case RepoType::RPMMD_e :
331 status = RepoStatus( rawpath + "/repodata/repomd.xml");
335 case RepoType::YAST2_e :
337 // the order of RepoStatus && RepoStatus matters! (#304310)
338 status = RepoStatus( rawpath + "/content") && (RepoStatus( rawpath + "/media.1/media"));
342 case RepoType::RPMPLAINDIR_e :
344 if ( PathInfo(Pathname(rawpath + "/cookie")).isExist() )
345 status = RepoStatus( rawpath + "/cookie");
349 case RepoType::NONE_e :
350 // Return default RepoStatus in case of RepoType::NONE
351 // indicating it should be created?
352 // ZYPP_THROW(RepoUnknownTypeException());
358 void RepoManager::touchIndexFile(const RepoInfo & info)
360 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
362 RepoType repokind = info.type();
363 if ( repokind.toEnum() == RepoType::NONE_e )
364 // unknown, probe the local metadata
365 repokind = probe(rawpath.asUrl());
366 // if still unknown, just return
367 if (repokind == RepoType::NONE_e)
371 switch ( repokind.toEnum() )
373 case RepoType::RPMMD_e :
374 p = Pathname(rawpath + "/repodata/repomd.xml");
377 case RepoType::YAST2_e :
378 p = Pathname(rawpath + "/content");
381 case RepoType::RPMPLAINDIR_e :
382 p = Pathname(rawpath + "/cookie");
385 case RepoType::NONE_e :
390 // touch the file, ignore error (they are logged anyway)
391 filesystem::touch(p);
394 bool RepoManager::checkIfToRefreshMetadata( const RepoInfo &info,
396 RawMetadataRefreshPolicy policy )
400 RepoStatus oldstatus;
401 RepoStatus newstatus;
405 MIL << "Going to try to check whether refresh is needed for " << url << endl;
407 repo::RepoType repokind = info.type();
409 // if the type is unknown, try probing.
410 switch ( repokind.toEnum() )
412 case RepoType::NONE_e:
414 repokind = probe(url);
420 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
421 filesystem::assert_dir(rawpath);
422 oldstatus = metadataStatus(info);
424 // now we've got the old (cached) status, we can decide repo.refresh.delay
425 if (policy != RefreshForced)
427 // difference in seconds
428 double diff = difftime(
429 (Date::ValueType)Date::now(),
430 (Date::ValueType)oldstatus.timestamp()) / 60;
432 DBG << "oldstatus: " << (Date::ValueType)oldstatus.timestamp() << endl;
433 DBG << "current time: " << (Date::ValueType)Date::now() << endl;
434 DBG << "last refresh = " << diff << " minutes ago" << endl;
436 if (diff < ZConfig::instance().repo_refresh_delay())
438 MIL << "Repository '" << info.alias()
439 << "' has been refreshed less than repo.refresh.delay ("
440 << ZConfig::instance().repo_refresh_delay()
441 << ") minutes ago. Advising to skip refresh" << endl;
446 // create temp dir as sibling of rawpath
447 filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( rawpath ) );
449 if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
450 ( repokind.toEnum() == RepoType::YAST2_e ) )
452 MediaSetAccess media(url);
453 shared_ptr<repo::Downloader> downloader_ptr;
455 if ( repokind.toEnum() == RepoType::RPMMD_e )
456 downloader_ptr.reset(new yum::Downloader(info.path()));
458 downloader_ptr.reset( new susetags::Downloader(info.path()));
460 RepoStatus newstatus = downloader_ptr->status(media);
461 bool refresh = false;
462 if ( oldstatus.checksum() == newstatus.checksum() )
464 MIL << "repo has not changed" << endl;
465 if ( policy == RefreshForced )
467 MIL << "refresh set to forced" << endl;
473 MIL << "repo has changed, going to refresh" << endl;
478 touchIndexFile(info);
482 else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
484 RepoStatus newstatus = parser::plaindir::dirStatus(url.getPathName());
485 bool refresh = false;
486 if ( oldstatus.checksum() == newstatus.checksum() )
488 MIL << "repo has not changed" << endl;
489 if ( policy == RefreshForced )
491 MIL << "refresh set to forced" << endl;
497 MIL << "repo has changed, going to refresh" << endl;
502 touchIndexFile(info);
508 ZYPP_THROW(RepoUnknownTypeException());
511 catch ( const Exception &e )
514 ERR << "refresh check failed for " << url << endl;
518 return true; // default
521 void RepoManager::refreshMetadata( const RepoInfo &info,
522 RawMetadataRefreshPolicy policy,
523 const ProgressData::ReceiverFnc & progress )
528 // we will throw this later if no URL checks out fine
529 RepoException rexception(_("Valid metadata not found at specified URL(s)"));
531 // try urls one by one
532 for ( RepoInfo::urls_const_iterator it = info.baseUrlsBegin(); it != info.baseUrlsEnd(); ++it )
538 // check whether to refresh metadata
539 // if the check fails for this url, it throws, so another url will be checked
540 if (!checkIfToRefreshMetadata(info, url, policy))
543 MIL << "Going to refresh metadata from " << url << endl;
545 repo::RepoType repokind = info.type();
547 // if the type is unknown, try probing.
548 switch ( repokind.toEnum() )
550 case RepoType::NONE_e:
552 repokind = probe(*it);
558 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
559 filesystem::assert_dir(rawpath);
561 // create temp dir as sibling of rawpath
562 filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( rawpath ) );
564 if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
565 ( repokind.toEnum() == RepoType::YAST2_e ) )
567 MediaSetAccess media(url);
568 shared_ptr<repo::Downloader> downloader_ptr;
570 if ( repokind.toEnum() == RepoType::RPMMD_e )
571 downloader_ptr.reset(new yum::Downloader(info.path()));
573 downloader_ptr.reset( new susetags::Downloader(info.path()));
576 * Given a downloader, sets the other repos raw metadata
577 * path as cache paths for the fetcher, so if another
578 * repo has the same file, it will not download it
579 * but copy it from the other repository
581 std::list<RepoInfo> repos = knownRepositories();
582 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
586 downloader_ptr->addCachePath(rawcache_path_for_repoinfo( _pimpl->options, *it ));
589 downloader_ptr->download( media, tmpdir.path());
591 else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
593 RepoStatus newstatus = parser::plaindir::dirStatus(url.getPathName());
595 std::ofstream file(( tmpdir.path() + "/cookie").c_str());
597 ZYPP_THROW (Exception( "Can't open " + tmpdir.path().asString() + "/cookie" ) );
600 file << newstatus.checksum() << endl;
606 ZYPP_THROW(RepoUnknownTypeException());
609 // ok we have the metadata, now exchange
611 TmpDir oldmetadata( TmpDir::makeSibling( rawpath ) );
612 filesystem::rename( rawpath, oldmetadata.path() );
613 // move the just downloaded there
614 filesystem::rename( tmpdir.path(), rawpath );
618 catch ( const Exception &e )
621 ERR << "Trying another url..." << endl;
623 // remember the exception caught for the *first URL*
624 // if all other URLs fail, the rexception will be thrown with the
625 // cause of the problem of the first URL remembered
626 if (it == info.baseUrlsBegin())
627 rexception.remember(e);
630 ERR << "No more urls..." << endl;
631 ZYPP_THROW(rexception);
634 ////////////////////////////////////////////////////////////////////////////
636 void RepoManager::cleanMetadata( const RepoInfo &info,
637 const ProgressData::ReceiverFnc & progressfnc )
639 ProgressData progress(100);
640 progress.sendTo(progressfnc);
642 filesystem::recursive_rmdir(rawcache_path_for_repoinfo(_pimpl->options, info));
646 void RepoManager::buildCache( const RepoInfo &info,
647 CacheBuildPolicy policy,
648 const ProgressData::ReceiverFnc & progressrcv )
651 Pathname rawpath = rawcache_path_for_repoinfo(_pimpl->options, info);
653 cache::CacheStore store(_pimpl->options.repoCachePath);
655 RepoStatus raw_metadata_status = metadataStatus(info);
656 if ( raw_metadata_status.empty() )
658 ZYPP_THROW(RepoMetadataException(info));
661 bool needs_cleaning = false;
662 if ( store.isCached( info.alias() ) )
664 MIL << info.alias() << " is already cached." << endl;
665 data::RecordId id = store.lookupRepository(info.alias());
666 RepoStatus cache_status = store.repositoryStatus(id);
668 if ( cache_status.checksum() == raw_metadata_status.checksum() )
670 MIL << info.alias() << " cache is up to date with metadata." << endl;
671 if ( policy == BuildIfNeeded ) {
675 MIL << info.alias() << " cache rebuild is forced" << endl;
679 needs_cleaning = true;
682 ProgressData progress(100);
683 callback::SendReport<ProgressReport> report;
684 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
685 progress.name(str::form(_("Building repository '%s' cache"), info.name().c_str()));
689 cleanCacheInternal( store, info);
691 MIL << info.alias() << " building cache..." << endl;
692 data::RecordId id = store.lookupOrAppendRepository(info.alias());
694 repo::RepoType repokind = info.type();
696 // if the type is unknown, try probing.
697 switch ( repokind.toEnum() )
699 case RepoType::NONE_e:
700 // unknown, probe the local metadata
701 repokind = probe(rawpath.asUrl());
708 switch ( repokind.toEnum() )
710 case RepoType::RPMMD_e :
712 CombinedProgressData subprogrcv( progress, 100);
713 parser::yum::RepoParser parser(id, store, parser::yum::RepoParserOpts(), subprogrcv);
714 parser.parse(rawpath);
718 case RepoType::YAST2_e :
720 CombinedProgressData subprogrcv( progress, 100);
721 parser::susetags::RepoParser parser(id, store, subprogrcv);
722 parser.parse(rawpath);
726 case RepoType::RPMPLAINDIR_e :
728 CombinedProgressData subprogrcv( progress, 100);
729 InputStream is(rawpath + "cookie");
731 getline( is.stream(), buffer);
733 parser::plaindir::RepoParser parser(id, store, subprogrcv);
734 parser.parse(url.getPathName());
738 ZYPP_THROW(RepoUnknownTypeException());
741 // update timestamp and checksum
742 store.updateRepositoryStatus(id, raw_metadata_status);
744 MIL << "Commit cache.." << endl;
749 ////////////////////////////////////////////////////////////////////////////
751 repo::RepoType RepoManager::probe( const Url &url ) const
753 if ( url.getScheme() == "dir" && ! PathInfo( url.getPathName() ).isDir() )
755 // Handle non existing local directory in advance, as
756 // MediaSetAccess does not support it.
757 return repo::RepoType::NONE;
762 MediaSetAccess access(url);
763 if ( access.doesFileExist("/repodata/repomd.xml") )
764 return repo::RepoType::RPMMD;
765 if ( access.doesFileExist("/content") )
766 return repo::RepoType::YAST2;
768 // if it is a local url of type dir
769 if ( (! media::MediaManager::downloads(url)) && ( url.getScheme() == "dir" ) )
771 Pathname path = Pathname(url.getPathName());
772 if ( PathInfo(path).isDir() )
774 // allow empty dirs for now
775 return repo::RepoType::RPMPLAINDIR;
779 catch ( const media::MediaException &e )
782 RepoException enew("Error trying to read from " + url.asString());
786 catch ( const Exception &e )
789 Exception enew("Unknown error reading from " + url.asString());
794 return repo::RepoType::NONE;
797 ////////////////////////////////////////////////////////////////////////////
799 void RepoManager::cleanCache( const RepoInfo &info,
800 const ProgressData::ReceiverFnc & progressrcv )
802 cache::CacheStore store(_pimpl->options.repoCachePath);
803 cleanCacheInternal( store, info, progressrcv );
807 ////////////////////////////////////////////////////////////////////////////
809 bool RepoManager::isCached( const RepoInfo &info ) const
811 cache::CacheStore store(_pimpl->options.repoCachePath);
812 return store.isCached(info.alias());
815 RepoStatus RepoManager::cacheStatus( const RepoInfo &info ) const
817 cache::CacheStore store(_pimpl->options.repoCachePath);
818 data::RecordId id = store.lookupRepository(info.alias());
819 RepoStatus cache_status = store.repositoryStatus(id);
823 Repository RepoManager::createFromCache( const RepoInfo &info,
824 const ProgressData::ReceiverFnc & progressrcv )
826 callback::SendReport<ProgressReport> report;
827 ProgressData progress;
828 progress.sendTo(ProgressReportAdaptor( progressrcv, report ));
829 //progress.sendTo( progressrcv );
830 progress.name(str::form(_("Reading repository '%s' cache"), info.name().c_str()));
832 cache::CacheStore store(_pimpl->options.repoCachePath);
834 if ( ! store.isCached( info.alias() ) )
835 ZYPP_THROW(RepoNotCachedException());
837 MIL << "Repository " << info.alias() << " is cached" << endl;
839 data::RecordId id = store.lookupRepository(info.alias());
841 CombinedProgressData subprogrcv(progress);
843 repo::cached::RepoOptions opts( info, _pimpl->options.repoCachePath, id );
844 opts.readingResolvablesProgress = subprogrcv;
845 repo::cached::RepoImpl::Ptr repoimpl =
846 new repo::cached::RepoImpl( opts );
848 repoimpl->resolvables();
849 // read the resolvables from cache
850 return Repository(repoimpl);
853 ////////////////////////////////////////////////////////////////////////////
856 * Generate a non existing filename in a directory, using a base
857 * name. For example if a directory contains 3 files
863 * If you try to generate a unique filename for this directory,
864 * based on "ruu" you will get "ruu", but if you use the base
865 * "foo" you will get "foo_1"
867 * \param dir Directory where the file needs to be unique
868 * \param basefilename string to base the filename on.
870 static Pathname generate_non_existing_name( const Pathname &dir,
871 const std::string &basefilename )
873 string final_filename = basefilename;
875 while ( PathInfo(dir + final_filename).isExist() )
877 final_filename = basefilename + "_" + str::numstring(counter);
880 return dir + Pathname(final_filename);
883 ////////////////////////////////////////////////////////////////////////////
886 * \short Generate a related filename from a repo info
888 * From a repo info, it will try to use the alias as a filename
889 * escaping it if necessary. Other fallbacks can be added to
890 * this function in case there is no way to use the alias
892 static std::string generate_filename( const RepoInfo &info )
896 std::string filename = info.alias();
897 // replace slashes with underscores
898 size_t pos = filename.find(fnd);
899 while(pos!=string::npos)
901 filename.replace(pos,fnd.length(),rep);
902 pos = filename.find(fnd,pos+rep.length());
904 filename = Pathname(filename).extend(".repo").asString();
905 MIL << "generating filename for repo [" << info.alias() << "] : '" << filename << "'" << endl;
910 ////////////////////////////////////////////////////////////////////////////
912 void RepoManager::addRepository( const RepoInfo &info,
913 const ProgressData::ReceiverFnc & progressrcv )
917 ProgressData progress(100);
918 callback::SendReport<ProgressReport> report;
919 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
920 progress.name(str::form(_("Adding repository '%s'"), info.name().c_str()));
923 std::list<RepoInfo> repos = knownRepositories();
924 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
928 if ( info.alias() == (*it).alias() )
929 ZYPP_THROW(RepoAlreadyExistsException(info.alias()));
932 RepoInfo tosave = info;
934 // check the first url for now
935 if ( ZConfig::instance().repo_add_probe()
936 || ( tosave.type() == RepoType::NONE && tosave.enabled()) )
938 DBG << "unknown repository type, probing" << endl;
941 probedtype = probe(*tosave.baseUrlsBegin());
942 if ( tosave.baseUrlsSize() > 0 )
944 if ( probedtype == RepoType::NONE )
945 ZYPP_THROW(RepoUnknownTypeException());
947 tosave.setType(probedtype);
953 // assert the directory exists
954 filesystem::assert_dir(_pimpl->options.knownReposPath);
956 Pathname repofile = generate_non_existing_name(_pimpl->options.knownReposPath,
957 generate_filename(tosave));
958 // now we have a filename that does not exists
959 MIL << "Saving repo in " << repofile << endl;
961 std::ofstream file(repofile.c_str());
963 ZYPP_THROW (Exception( "Can't open " + repofile.asString() ) );
966 tosave.dumpRepoOn(file);
968 MIL << "done" << endl;
971 void RepoManager::addRepositories( const Url &url,
972 const ProgressData::ReceiverFnc & progressrcv )
974 std::list<RepoInfo> knownrepos = knownRepositories();
975 std::list<RepoInfo> repos = readRepoFile(url);
976 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
980 // look if the alias is in the known repos.
981 for ( std::list<RepoInfo>::const_iterator kit = knownrepos.begin();
982 kit != knownrepos.end();
985 if ( (*it).alias() == (*kit).alias() )
987 ERR << "To be added repo " << (*it).alias() << " conflicts with existing repo " << (*kit).alias() << endl;
988 ZYPP_THROW(RepoAlreadyExistsException((*it).alias()));
993 string filename = Pathname(url.getPathName()).basename();
995 if ( filename == Pathname() )
996 ZYPP_THROW(RepoException("Invalid repo file name at " + url.asString() ));
998 // assert the directory exists
999 filesystem::assert_dir(_pimpl->options.knownReposPath);
1001 Pathname repofile = generate_non_existing_name(_pimpl->options.knownReposPath, filename);
1002 // now we have a filename that does not exists
1003 MIL << "Saving " << repos.size() << " repo" << ( repos.size() ? "s" : "" ) << " in " << repofile << endl;
1005 std::ofstream file(repofile.c_str());
1007 ZYPP_THROW (Exception( "Can't open " + repofile.asString() ) );
1010 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1014 MIL << "Saving " << (*it).alias() << endl;
1015 (*it).dumpRepoOn(file);
1017 MIL << "done" << endl;
1020 ////////////////////////////////////////////////////////////////////////////
1022 void RepoManager::removeRepository( const RepoInfo & info,
1023 const ProgressData::ReceiverFnc & progressrcv)
1025 ProgressData progress;
1026 callback::SendReport<ProgressReport> report;
1027 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1028 progress.name(str::form(_("Removing repository '%s'"), info.name().c_str()));
1030 MIL << "Going to delete repo " << info.alias() << endl;
1032 std::list<RepoInfo> repos = knownRepositories();
1033 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1037 // they can be the same only if the provided is empty, that means
1038 // the provided repo has no alias
1040 if ( (!info.alias().empty()) && ( info.alias() != (*it).alias() ) )
1043 // TODO match by url
1045 // we have a matcing repository, now we need to know
1046 // where it does come from.
1047 RepoInfo todelete = *it;
1048 if (todelete.filepath().empty())
1050 ZYPP_THROW(RepoException("Can't figure where the repo is stored"));
1054 // figure how many repos are there in the file:
1055 std::list<RepoInfo> filerepos = repositories_in_file(todelete.filepath());
1056 if ( (filerepos.size() == 1) && ( filerepos.front().alias() == todelete.alias() ) )
1058 // easy, only this one, just delete the file
1059 if ( filesystem::unlink(todelete.filepath()) != 0 )
1061 ZYPP_THROW(RepoException("Can't delete " + todelete.filepath().asString()));
1063 MIL << todelete.alias() << " sucessfully deleted." << endl;
1067 // there are more repos in the same file
1068 // write them back except the deleted one.
1070 //std::ofstream file(tmp.path().c_str());
1072 // assert the directory exists
1073 filesystem::assert_dir(todelete.filepath().dirname());
1075 std::ofstream file(todelete.filepath().c_str());
1077 //ZYPP_THROW (Exception( "Can't open " + tmp.path().asString() ) );
1078 ZYPP_THROW (Exception( "Can't open " + todelete.filepath().asString() ) );
1080 for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1081 fit != filerepos.end();
1084 if ( (*fit).alias() != todelete.alias() )
1085 (*fit).dumpRepoOn(file);
1089 CombinedProgressData subprogrcv(progress, 70);
1090 CombinedProgressData cleansubprogrcv(progress, 30);
1091 // now delete it from cache
1092 cleanCache( todelete, subprogrcv);
1093 // now delete metadata (#301037)
1094 cleanMetadata( todelete, cleansubprogrcv);
1095 MIL << todelete.alias() << " sucessfully deleted." << endl;
1097 } // else filepath is empty
1100 // should not be reached on a sucess workflow
1101 ZYPP_THROW(RepoNotFoundException(info));
1104 ////////////////////////////////////////////////////////////////////////////
1106 void RepoManager::modifyRepository( const std::string &alias,
1107 const RepoInfo & newinfo,
1108 const ProgressData::ReceiverFnc & progressrcv )
1110 RepoInfo toedit = getRepositoryInfo(alias);
1112 if (toedit.filepath().empty())
1114 ZYPP_THROW(RepoException("Can't figure where the repo is stored"));
1118 // figure how many repos are there in the file:
1119 std::list<RepoInfo> filerepos = repositories_in_file(toedit.filepath());
1121 // there are more repos in the same file
1122 // write them back except the deleted one.
1124 //std::ofstream file(tmp.path().c_str());
1126 // assert the directory exists
1127 filesystem::assert_dir(toedit.filepath().dirname());
1129 std::ofstream file(toedit.filepath().c_str());
1131 //ZYPP_THROW (Exception( "Can't open " + tmp.path().asString() ) );
1132 ZYPP_THROW (Exception( "Can't open " + toedit.filepath().asString() ) );
1134 for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1135 fit != filerepos.end();
1138 // if the alias is different, dump the original
1139 // if it is the same, dump the provided one
1140 if ( (*fit).alias() != toedit.alias() )
1141 (*fit).dumpRepoOn(file);
1143 newinfo.dumpRepoOn(file);
1148 ////////////////////////////////////////////////////////////////////////////
1150 RepoInfo RepoManager::getRepositoryInfo( const std::string &alias,
1151 const ProgressData::ReceiverFnc & progressrcv )
1153 std::list<RepoInfo> repos = knownRepositories();
1154 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1158 if ( (*it).alias() == alias )
1162 info.setAlias(info.alias());
1163 ZYPP_THROW(RepoNotFoundException(info));
1166 ////////////////////////////////////////////////////////////////////////////
1168 RepoInfo RepoManager::getRepositoryInfo( const Url & url,
1169 const url::ViewOption & urlview,
1170 const ProgressData::ReceiverFnc & progressrcv )
1172 std::list<RepoInfo> repos = knownRepositories();
1173 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1177 for(RepoInfo::urls_const_iterator urlit = (*it).baseUrlsBegin();
1178 urlit != (*it).baseUrlsEnd();
1181 if ((*urlit).asString(urlview) == url.asString(urlview))
1186 info.setAlias(info.alias());
1187 info.setBaseUrl(url);
1188 ZYPP_THROW(RepoNotFoundException(info));
1191 ////////////////////////////////////////////////////////////////////////////
1193 std::ostream & operator<<( std::ostream & str, const RepoManager & obj )
1195 return str << *obj._pimpl;
1198 /////////////////////////////////////////////////////////////////
1200 ///////////////////////////////////////////////////////////////////