1 /*---------------------------------------------------------------------\
3 | |__ / \ / / . \ . \ |
8 \---------------------------------------------------------------------*/
9 /** \file zypp/RepoManager.cc
20 #include "zypp/base/InputStream.h"
21 #include "zypp/base/Logger.h"
22 #include "zypp/base/Gettext.h"
23 #include "zypp/base/Function.h"
24 #include "zypp/base/Regex.h"
25 #include "zypp/PathInfo.h"
26 #include "zypp/TmpPath.h"
28 #include "zypp/repo/RepoException.h"
29 #include "zypp/RepoManager.h"
31 #include "zypp/media/MediaManager.h"
32 #include "zypp/MediaSetAccess.h"
33 #include "zypp/ExternalProgram.h"
34 #include "zypp/ManagedFile.h"
36 #include "zypp/parser/RepoFileReader.h"
37 #include "zypp/repo/yum/Downloader.h"
38 #include "zypp/parser/yum/RepoParser.h"
39 #include "zypp/repo/susetags/Downloader.h"
40 #include "zypp/parser/susetags/RepoParser.h"
42 #include "zypp/ZYppCallbacks.h"
45 #include "satsolver/pool.h"
46 #include "satsolver/repo.h"
47 #include "satsolver/repo_solv.h"
51 using namespace zypp::repo;
52 using namespace zypp::filesystem;
54 using namespace zypp::repo;
56 ///////////////////////////////////////////////////////////////////
58 { /////////////////////////////////////////////////////////////////
60 ///////////////////////////////////////////////////////////////////
62 // CLASS NAME : RepoManagerOptions
64 ///////////////////////////////////////////////////////////////////
66 RepoManagerOptions::RepoManagerOptions()
68 repoCachePath = ZConfig::instance().repoCachePath();
69 repoRawCachePath = ZConfig::instance().repoMetadataPath();
70 knownReposPath = ZConfig::instance().knownReposPath();
73 ////////////////////////////////////////////////////////////////////////////
76 * \short Simple callback to collect the results
78 * Classes like RepoFileParser call the callback
79 * once per each repo in a file.
81 * Passing this functor as callback, you can collect
82 * all resuls at the end, without dealing with async
97 bool collect( const RepoInfo &repo )
99 //MIL << "here in collector: " << repo.alias() << endl;
100 repos.push_back(repo);
101 //MIL << "added: " << repo.alias() << endl;
108 ////////////////////////////////////////////////////////////////////////////
111 * Reads RepoInfo's from a repo file.
113 * \param file pathname of the file to read.
115 static std::list<RepoInfo> repositories_in_file( const Pathname & file )
117 MIL << "repo file: " << file << endl;
118 RepoCollector collector;
119 parser::RepoFileReader parser( file, bind( &RepoCollector::collect, &collector, _1 ) );
120 return collector.repos;
123 ////////////////////////////////////////////////////////////////////////////
125 std::list<RepoInfo> readRepoFile(const Url & repo_file)
127 // no interface to download a specific file, using workaround:
128 //! \todo add MediaManager::provideFile(Url file_url) to easily access any file URLs? (no need for media access id or media_nr)
130 Pathname path(url.getPathName());
131 url.setPathName ("/");
132 MediaSetAccess access(url);
133 Pathname local = access.provideFile(path);
135 DBG << "reading repo file " << repo_file << ", local path: " << local << endl;
137 return repositories_in_file(local);
140 ////////////////////////////////////////////////////////////////////////////
143 * \short List of RepoInfo's from a directory
145 * Goes trough every file ending with ".repo" in a directory and adds all
146 * RepoInfo's contained in that file.
148 * \param dir pathname of the directory to read.
150 static std::list<RepoInfo> repositories_in_dir( const Pathname &dir )
152 MIL << "directory " << dir << endl;
153 list<RepoInfo> repos;
154 list<Pathname> entries;
155 if ( filesystem::readdir( entries, Pathname(dir), false ) != 0 )
156 ZYPP_THROW(Exception("failed to read directory"));
158 str::regex allowedRepoExt("^\\.repo(_[0-9]+)?$");
159 for ( list<Pathname>::const_iterator it = entries.begin(); it != entries.end(); ++it )
161 if (str::regex_match(it->extension(), allowedRepoExt))
163 list<RepoInfo> tmp = repositories_in_file( *it );
164 repos.insert( repos.end(), tmp.begin(), tmp.end() );
166 //std::copy( collector.repos.begin(), collector.repos.end(), std::back_inserter(repos));
167 //MIL << "ok" << endl;
173 ////////////////////////////////////////////////////////////////////////////
175 static void assert_alias( const RepoInfo &info )
177 if (info.alias().empty())
178 ZYPP_THROW(RepoNoAliasException());
181 ////////////////////////////////////////////////////////////////////////////
183 static void assert_urls( const RepoInfo &info )
185 if (info.baseUrlsEmpty())
186 ZYPP_THROW(RepoNoUrlException());
189 ////////////////////////////////////////////////////////////////////////////
192 * \short Calculates the raw cache path for a repository
194 static Pathname rawcache_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info )
197 return opt.repoRawCachePath + info.alias();
200 ///////////////////////////////////////////////////////////////////
202 // CLASS NAME : RepoManager::Impl
204 ///////////////////////////////////////////////////////////////////
207 * \short RepoManager implementation.
209 struct RepoManager::Impl
211 Impl( const RepoManagerOptions &opt )
222 RepoManagerOptions options;
224 map<string, RepoInfo> _repoinfos;
227 /** Offer default Impl. */
228 static shared_ptr<Impl> nullimpl()
230 static shared_ptr<Impl> _nullimpl( new Impl );
235 friend Impl * rwcowClone<Impl>( const Impl * rhs );
236 /** clone for RWCOW_pointer */
238 { return new Impl( *this ); }
241 ///////////////////////////////////////////////////////////////////
243 /** \relates RepoManager::Impl Stream output */
244 inline std::ostream & operator<<( std::ostream & str, const RepoManager::Impl & obj )
246 return str << "RepoManager::Impl";
249 ///////////////////////////////////////////////////////////////////
251 // CLASS NAME : RepoManager
253 ///////////////////////////////////////////////////////////////////
255 RepoManager::RepoManager( const RepoManagerOptions &opt )
256 : _pimpl( new Impl(opt) )
259 ////////////////////////////////////////////////////////////////////////////
261 RepoManager::~RepoManager()
264 ////////////////////////////////////////////////////////////////////////////
266 std::list<RepoInfo> RepoManager::knownRepositories() const
270 if ( PathInfo(_pimpl->options.knownReposPath).isExist() )
272 RepoInfoList repos = repositories_in_dir(_pimpl->options.knownReposPath);
273 for ( RepoInfoList::iterator it = repos.begin();
277 // set the metadata path for the repo
278 Pathname metadata_path = rawcache_path_for_repoinfo(_pimpl->options, (*it));
279 (*it).setMetadataPath(metadata_path);
284 return std::list<RepoInfo>();
289 ////////////////////////////////////////////////////////////////////////////
291 Pathname RepoManager::metadataPath( const RepoInfo &info ) const
293 return rawcache_path_for_repoinfo(_pimpl->options, info );
296 ////////////////////////////////////////////////////////////////////////////
298 RepoStatus RepoManager::metadataStatus( const RepoInfo &info ) const
300 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
301 RepoType repokind = info.type();
304 switch ( repokind.toEnum() )
306 case RepoType::NONE_e:
307 // unknown, probe the local metadata
308 repokind = probe(rawpath.asUrl());
314 switch ( repokind.toEnum() )
316 case RepoType::RPMMD_e :
318 status = RepoStatus( rawpath + "/repodata/repomd.xml");
322 case RepoType::YAST2_e :
324 // the order of RepoStatus && RepoStatus matters! (#304310)
325 status = RepoStatus( rawpath + "/content") && (RepoStatus( rawpath + "/media.1/media"));
329 case RepoType::RPMPLAINDIR_e :
331 if ( PathInfo(Pathname(rawpath + "/cookie")).isExist() )
332 status = RepoStatus( rawpath + "/cookie");
336 case RepoType::NONE_e :
337 // Return default RepoStatus in case of RepoType::NONE
338 // indicating it should be created?
339 // ZYPP_THROW(RepoUnknownTypeException());
345 void RepoManager::touchIndexFile(const RepoInfo & info)
347 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
349 RepoType repokind = info.type();
350 if ( repokind.toEnum() == RepoType::NONE_e )
351 // unknown, probe the local metadata
352 repokind = probe(rawpath.asUrl());
353 // if still unknown, just return
354 if (repokind == RepoType::NONE_e)
358 switch ( repokind.toEnum() )
360 case RepoType::RPMMD_e :
361 p = Pathname(rawpath + "/repodata/repomd.xml");
364 case RepoType::YAST2_e :
365 p = Pathname(rawpath + "/content");
368 case RepoType::RPMPLAINDIR_e :
369 p = Pathname(rawpath + "/cookie");
372 case RepoType::NONE_e :
377 // touch the file, ignore error (they are logged anyway)
378 filesystem::touch(p);
381 bool RepoManager::checkIfToRefreshMetadata( const RepoInfo &info,
383 RawMetadataRefreshPolicy policy )
387 RepoStatus oldstatus;
388 RepoStatus newstatus;
392 MIL << "Going to try to check whether refresh is needed for " << url << endl;
394 repo::RepoType repokind = info.type();
396 // if the type is unknown, try probing.
397 switch ( repokind.toEnum() )
399 case RepoType::NONE_e:
401 repokind = probe(url);
407 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
408 filesystem::assert_dir(rawpath);
409 oldstatus = metadataStatus(info);
411 // now we've got the old (cached) status, we can decide repo.refresh.delay
412 if (policy != RefreshForced)
414 // difference in seconds
415 double diff = difftime(
416 (Date::ValueType)Date::now(),
417 (Date::ValueType)oldstatus.timestamp()) / 60;
419 DBG << "oldstatus: " << (Date::ValueType)oldstatus.timestamp() << endl;
420 DBG << "current time: " << (Date::ValueType)Date::now() << endl;
421 DBG << "last refresh = " << diff << " minutes ago" << endl;
423 if (diff < ZConfig::instance().repo_refresh_delay())
425 MIL << "Repository '" << info.alias()
426 << "' has been refreshed less than repo.refresh.delay ("
427 << ZConfig::instance().repo_refresh_delay()
428 << ") minutes ago. Advising to skip refresh" << endl;
433 // create temp dir as sibling of rawpath
434 filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( rawpath ) );
436 if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
437 ( repokind.toEnum() == RepoType::YAST2_e ) )
439 MediaSetAccess media(url);
440 shared_ptr<repo::Downloader> downloader_ptr;
442 if ( repokind.toEnum() == RepoType::RPMMD_e )
443 downloader_ptr.reset(new yum::Downloader(info.path()));
445 downloader_ptr.reset( new susetags::Downloader(info.path()));
447 RepoStatus newstatus = downloader_ptr->status(media);
448 bool refresh = false;
449 if ( oldstatus.checksum() == newstatus.checksum() )
451 MIL << "repo has not changed" << endl;
452 if ( policy == RefreshForced )
454 MIL << "refresh set to forced" << endl;
460 MIL << "repo has changed, going to refresh" << endl;
465 touchIndexFile(info);
470 else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
472 RepoStatus newstatus = parser::plaindir::dirStatus(url.getPathName());
473 bool refresh = false;
474 if ( oldstatus.checksum() == newstatus.checksum() )
476 MIL << "repo has not changed" << endl;
477 if ( policy == RefreshForced )
479 MIL << "refresh set to forced" << endl;
485 MIL << "repo has changed, going to refresh" << endl;
490 touchIndexFile(info);
497 ZYPP_THROW(RepoUnknownTypeException());
500 catch ( const Exception &e )
503 ERR << "refresh check failed for " << url << endl;
507 return true; // default
510 void RepoManager::refreshMetadata( const RepoInfo &info,
511 RawMetadataRefreshPolicy policy,
512 const ProgressData::ReceiverFnc & progress )
517 // we will throw this later if no URL checks out fine
518 RepoException rexception(_("Valid metadata not found at specified URL(s)"));
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());
581 else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
583 RepoStatus newstatus = parser::plaindir::dirStatus(url.getPathName());
585 std::ofstream file(( tmpdir.path() + "/cookie").c_str());
587 ZYPP_THROW (Exception( "Can't open " + tmpdir.path().asString() + "/cookie" ) );
590 file << newstatus.checksum() << endl;
597 ZYPP_THROW(RepoUnknownTypeException());
600 // ok we have the metadata, now exchange
602 TmpDir oldmetadata( TmpDir::makeSibling( rawpath ) );
603 filesystem::rename( rawpath, oldmetadata.path() );
604 // move the just downloaded there
605 filesystem::rename( tmpdir.path(), rawpath );
609 catch ( const Exception &e )
612 ERR << "Trying another url..." << endl;
614 // remember the exception caught for the *first URL*
615 // if all other URLs fail, the rexception will be thrown with the
616 // cause of the problem of the first URL remembered
617 if (it == info.baseUrlsBegin())
618 rexception.remember(e);
621 ERR << "No more urls..." << endl;
622 ZYPP_THROW(rexception);
625 ////////////////////////////////////////////////////////////////////////////
627 void RepoManager::cleanMetadata( const RepoInfo &info,
628 const ProgressData::ReceiverFnc & progressfnc )
630 ProgressData progress(100);
631 progress.sendTo(progressfnc);
633 filesystem::recursive_rmdir(rawcache_path_for_repoinfo(_pimpl->options, info));
637 void RepoManager::buildCache( const RepoInfo &info,
638 CacheBuildPolicy policy,
639 const ProgressData::ReceiverFnc & progressrcv )
642 Pathname rawpath = rawcache_path_for_repoinfo(_pimpl->options, info);
644 Pathname base = _pimpl->options.repoCachePath + info.escaped_alias();
645 Pathname solvfile = base.extend(".solv");
647 //cache::SolvStore store(_pimpl->options.repoCachePath);
649 RepoStatus raw_metadata_status = metadataStatus(info);
650 if ( raw_metadata_status.empty() )
652 ZYPP_THROW(RepoMetadataException(info));
655 bool needs_cleaning = false;
656 if ( isCached( info ) )
658 MIL << info.alias() << " is already cached." << endl;
659 //data::RecordId id = store.lookupRepository(info.alias());
660 RepoStatus cache_status = cacheStatus(info);
662 if ( cache_status.checksum() == raw_metadata_status.checksum() )
664 MIL << info.alias() << " cache is up to date with metadata." << endl;
665 if ( policy == BuildIfNeeded ) {
669 MIL << info.alias() << " cache rebuild is forced" << endl;
673 needs_cleaning = true;
676 ProgressData progress(100);
677 callback::SendReport<ProgressReport> report;
678 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
679 progress.name(str::form(_("Building repository '%s' cache"), info.name().c_str()));
684 // Pathname name = _pimpl->options.repoCachePath;
685 // //data::RecordId id = store.lookupRepository(info.alias());
688 // name += os.str() + ".solv";
690 // 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());
710 MIL << "repo type is " << repokind << endl;
712 switch ( repokind.toEnum() )
714 case RepoType::RPMMD_e :
715 case RepoType::YAST2_e :
717 MIL << "Executing solv converter" << endl;
718 // Take care we unlink the solvfile on exception
719 ManagedFile guard( solvfile, filesystem::unlink );
721 string cmd( str::form( "repo2solv.sh \"%s\" > \"%s\"", rawpath.c_str(), solvfile.c_str() ) );
722 ExternalProgram prog( cmd, ExternalProgram::Stderr_To_Stdout );
723 for ( string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() ) {
724 MIL << " " << output;
726 int ret = prog.close();
728 ZYPP_THROW(RepoUnknownTypeException());
731 guard.resetDispose();
735 ZYPP_THROW(Exception("Unhandled repostory type"));
739 switch ( repokind.toEnum() )
741 case RepoType::RPMMD_e :
744 CombinedProgressData subprogrcv( progress, 100);
745 parser::yum::RepoParser parser(id, store, parser::yum::RepoParserOpts(), subprogrcv);
746 parser.parse(rawpath);
750 case RepoType::YAST2_e :
753 CombinedProgressData subprogrcv( progress, 100);
754 parser::susetags::RepoParser parser(id, store, subprogrcv);
755 parser.parse(rawpath);
761 case RepoType::RPMPLAINDIR_e :
763 CombinedProgressData subprogrcv( progress, 100);
764 InputStream is(rawpath + "cookie");
766 getline( is.stream(), buffer);
768 parser::plaindir::RepoParser parser(id, store, subprogrcv);
769 parser.parse(url.getPathName());
774 ZYPP_THROW(RepoUnknownTypeException());
777 // update timestamp and checksum
778 //store.updateRepositoryStatus(id, raw_metadata_status);
779 setCacheStatus(info.escaped_alias(), raw_metadata_status);
780 MIL << "Commit cache.." << endl;
785 ////////////////////////////////////////////////////////////////////////////
787 repo::RepoType RepoManager::probe( const Url &url ) const
789 if ( url.getScheme() == "dir" && ! PathInfo( url.getPathName() ).isDir() )
791 // Handle non existing local directory in advance, as
792 // MediaSetAccess does not support it.
793 return repo::RepoType::NONE;
798 MediaSetAccess access(url);
799 if ( access.doesFileExist("/repodata/repomd.xml") )
800 return repo::RepoType::RPMMD;
801 if ( access.doesFileExist("/content") )
802 return repo::RepoType::YAST2;
804 // if it is a local url of type dir
805 if ( (! media::MediaManager::downloads(url)) && ( url.getScheme() == "dir" ) )
807 Pathname path = Pathname(url.getPathName());
808 if ( PathInfo(path).isDir() )
810 // allow empty dirs for now
811 return repo::RepoType::RPMPLAINDIR;
815 catch ( const media::MediaException &e )
818 RepoException enew("Error trying to read from " + url.asString());
822 catch ( const Exception &e )
825 Exception enew("Unknown error reading from " + url.asString());
830 return repo::RepoType::NONE;
833 ////////////////////////////////////////////////////////////////////////////
835 void RepoManager::cleanCache( const RepoInfo &info,
836 const ProgressData::ReceiverFnc & progressrcv )
838 Pathname name = _pimpl->options.repoCachePath;
839 name += info.escaped_alias() + ".solv";
843 ////////////////////////////////////////////////////////////////////////////
845 bool RepoManager::isCached( const RepoInfo &info ) const
847 Pathname name = _pimpl->options.repoCachePath;
848 return PathInfo(name + Pathname(info.escaped_alias()).extend(".solv")).isExist();
851 RepoStatus RepoManager::cacheStatus( const RepoInfo &info ) const
854 Pathname base = _pimpl->options.repoCachePath + info.escaped_alias();
855 Pathname cookiefile = base.extend(".cookie");
857 return RepoStatus::fromCookieFile(cookiefile);
860 void RepoManager::setCacheStatus( const string &alias, const RepoStatus &status )
862 Pathname base = _pimpl->options.repoCachePath + alias;
863 Pathname cookiefile = base.extend(".cookie");
865 status.saveToCookieFile(cookiefile);
868 void RepoManager::loadFromCache( const RepoInfo &info,
869 const ProgressData::ReceiverFnc & progressrcv )
872 sat::Pool satpool( sat::Pool::instance() );
873 string alias = info.escaped_alias();
875 Pathname solvfile = (_pimpl->options.repoCachePath + alias).extend(".solv");
877 if ( ! PathInfo(solvfile).isExist() )
878 ZYPP_THROW(RepoNotCachedException());
880 sat::Repo repo = satpool.addRepoSolv(solvfile, info);
883 ////////////////////////////////////////////////////////////////////////////
886 * Generate a non existing filename in a directory, using a base
887 * name. For example if a directory contains 3 files
893 * If you try to generate a unique filename for this directory,
894 * based on "ruu" you will get "ruu", but if you use the base
895 * "foo" you will get "foo_1"
897 * \param dir Directory where the file needs to be unique
898 * \param basefilename string to base the filename on.
900 static Pathname generate_non_existing_name( const Pathname &dir,
901 const std::string &basefilename )
903 string final_filename = basefilename;
905 while ( PathInfo(dir + final_filename).isExist() )
907 final_filename = basefilename + "_" + str::numstring(counter);
910 return dir + Pathname(final_filename);
913 ////////////////////////////////////////////////////////////////////////////
916 * \short Generate a related filename from a repo info
918 * From a repo info, it will try to use the alias as a filename
919 * escaping it if necessary. Other fallbacks can be added to
920 * this function in case there is no way to use the alias
922 static std::string generate_filename( const RepoInfo &info )
926 std::string filename = info.alias();
927 // replace slashes with underscores
928 size_t pos = filename.find(fnd);
929 while(pos!=string::npos)
931 filename.replace(pos,fnd.length(),rep);
932 pos = filename.find(fnd,pos+rep.length());
934 filename = Pathname(filename).extend(".repo").asString();
935 MIL << "generating filename for repo [" << info.alias() << "] : '" << filename << "'" << endl;
940 ////////////////////////////////////////////////////////////////////////////
942 void RepoManager::addRepository( const RepoInfo &info,
943 const ProgressData::ReceiverFnc & progressrcv )
947 ProgressData progress(100);
948 callback::SendReport<ProgressReport> report;
949 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
950 progress.name(str::form(_("Adding repository '%s'"), info.name().c_str()));
953 std::list<RepoInfo> repos = knownRepositories();
954 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
958 if ( info.alias() == (*it).alias() )
959 ZYPP_THROW(RepoAlreadyExistsException(info.alias()));
962 RepoInfo tosave = info;
964 // check the first url for now
965 if ( ZConfig::instance().repo_add_probe()
966 || ( tosave.type() == RepoType::NONE && tosave.enabled()) )
968 DBG << "unknown repository type, probing" << endl;
971 probedtype = probe(*tosave.baseUrlsBegin());
972 if ( tosave.baseUrlsSize() > 0 )
974 if ( probedtype == RepoType::NONE )
975 ZYPP_THROW(RepoUnknownTypeException());
977 tosave.setType(probedtype);
983 // assert the directory exists
984 filesystem::assert_dir(_pimpl->options.knownReposPath);
986 Pathname repofile = generate_non_existing_name(_pimpl->options.knownReposPath,
987 generate_filename(tosave));
988 // now we have a filename that does not exists
989 MIL << "Saving repo in " << repofile << endl;
991 std::ofstream file(repofile.c_str());
993 ZYPP_THROW (Exception( "Can't open " + repofile.asString() ) );
996 tosave.dumpRepoOn(file);
998 MIL << "done" << endl;
1001 void RepoManager::addRepositories( const Url &url,
1002 const ProgressData::ReceiverFnc & progressrcv )
1004 std::list<RepoInfo> knownrepos = knownRepositories();
1005 std::list<RepoInfo> repos = readRepoFile(url);
1006 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1010 // look if the alias is in the known repos.
1011 for ( std::list<RepoInfo>::const_iterator kit = knownrepos.begin();
1012 kit != knownrepos.end();
1015 if ( (*it).alias() == (*kit).alias() )
1017 ERR << "To be added repo " << (*it).alias() << " conflicts with existing repo " << (*kit).alias() << endl;
1018 ZYPP_THROW(RepoAlreadyExistsException((*it).alias()));
1023 string filename = Pathname(url.getPathName()).basename();
1025 if ( filename == Pathname() )
1026 ZYPP_THROW(RepoException("Invalid repo file name at " + url.asString() ));
1028 // assert the directory exists
1029 filesystem::assert_dir(_pimpl->options.knownReposPath);
1031 Pathname repofile = generate_non_existing_name(_pimpl->options.knownReposPath, filename);
1032 // now we have a filename that does not exists
1033 MIL << "Saving " << repos.size() << " repo" << ( repos.size() ? "s" : "" ) << " in " << repofile << endl;
1035 std::ofstream file(repofile.c_str());
1037 ZYPP_THROW (Exception( "Can't open " + repofile.asString() ) );
1040 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1044 MIL << "Saving " << (*it).alias() << endl;
1045 (*it).dumpRepoOn(file);
1047 MIL << "done" << endl;
1050 ////////////////////////////////////////////////////////////////////////////
1052 void RepoManager::removeRepository( const RepoInfo & info,
1053 const ProgressData::ReceiverFnc & progressrcv)
1055 ProgressData progress;
1056 callback::SendReport<ProgressReport> report;
1057 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1058 progress.name(str::form(_("Removing repository '%s'"), info.name().c_str()));
1060 MIL << "Going to delete repo " << info.alias() << endl;
1062 std::list<RepoInfo> repos = knownRepositories();
1063 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1067 // they can be the same only if the provided is empty, that means
1068 // the provided repo has no alias
1070 if ( (!info.alias().empty()) && ( info.alias() != (*it).alias() ) )
1073 // TODO match by url
1075 // we have a matcing repository, now we need to know
1076 // where it does come from.
1077 RepoInfo todelete = *it;
1078 if (todelete.filepath().empty())
1080 ZYPP_THROW(RepoException("Can't figure where the repo is stored"));
1084 // figure how many repos are there in the file:
1085 std::list<RepoInfo> filerepos = repositories_in_file(todelete.filepath());
1086 if ( (filerepos.size() == 1) && ( filerepos.front().alias() == todelete.alias() ) )
1088 // easy, only this one, just delete the file
1089 if ( filesystem::unlink(todelete.filepath()) != 0 )
1091 ZYPP_THROW(RepoException("Can't delete " + todelete.filepath().asString()));
1093 MIL << todelete.alias() << " sucessfully deleted." << endl;
1097 // there are more repos in the same file
1098 // write them back except the deleted one.
1100 //std::ofstream file(tmp.path().c_str());
1102 // assert the directory exists
1103 filesystem::assert_dir(todelete.filepath().dirname());
1105 std::ofstream file(todelete.filepath().c_str());
1107 //ZYPP_THROW (Exception( "Can't open " + tmp.path().asString() ) );
1108 ZYPP_THROW (Exception( "Can't open " + todelete.filepath().asString() ) );
1110 for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1111 fit != filerepos.end();
1114 if ( (*fit).alias() != todelete.alias() )
1115 (*fit).dumpRepoOn(file);
1119 CombinedProgressData subprogrcv(progress, 70);
1120 CombinedProgressData cleansubprogrcv(progress, 30);
1121 // now delete it from cache
1122 if ( isCached(todelete) )
1123 cleanCache( todelete, subprogrcv);
1124 // now delete metadata (#301037)
1125 cleanMetadata( todelete, cleansubprogrcv);
1126 MIL << todelete.alias() << " sucessfully deleted." << endl;
1128 } // else filepath is empty
1131 // should not be reached on a sucess workflow
1132 ZYPP_THROW(RepoNotFoundException(info));
1135 ////////////////////////////////////////////////////////////////////////////
1137 void RepoManager::modifyRepository( const std::string &alias,
1138 const RepoInfo & newinfo,
1139 const ProgressData::ReceiverFnc & progressrcv )
1141 RepoInfo toedit = getRepositoryInfo(alias);
1143 // check if the new alias already exists when renaming the repo
1144 if (alias != newinfo.alias())
1146 std::list<RepoInfo> repos = knownRepositories();
1147 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1151 if ( newinfo.alias() == (*it).alias() )
1152 ZYPP_THROW(RepoAlreadyExistsException(newinfo.alias()));
1156 if (toedit.filepath().empty())
1158 ZYPP_THROW(RepoException("Can't figure where the repo is stored"));
1162 // figure how many repos are there in the file:
1163 std::list<RepoInfo> filerepos = repositories_in_file(toedit.filepath());
1165 // there are more repos in the same file
1166 // write them back except the deleted one.
1168 //std::ofstream file(tmp.path().c_str());
1170 // assert the directory exists
1171 filesystem::assert_dir(toedit.filepath().dirname());
1173 std::ofstream file(toedit.filepath().c_str());
1175 //ZYPP_THROW (Exception( "Can't open " + tmp.path().asString() ) );
1176 ZYPP_THROW (Exception( "Can't open " + toedit.filepath().asString() ) );
1178 for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1179 fit != filerepos.end();
1182 // if the alias is different, dump the original
1183 // if it is the same, dump the provided one
1184 if ( (*fit).alias() != toedit.alias() )
1185 (*fit).dumpRepoOn(file);
1187 newinfo.dumpRepoOn(file);
1192 ////////////////////////////////////////////////////////////////////////////
1194 RepoInfo RepoManager::getRepositoryInfo( const std::string &alias,
1195 const ProgressData::ReceiverFnc & progressrcv )
1197 std::list<RepoInfo> repos = knownRepositories();
1198 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1202 if ( (*it).alias() == alias )
1206 info.setAlias(info.alias());
1207 ZYPP_THROW(RepoNotFoundException(info));
1210 ////////////////////////////////////////////////////////////////////////////
1212 RepoInfo RepoManager::getRepositoryInfo( const Url & url,
1213 const url::ViewOption & urlview,
1214 const ProgressData::ReceiverFnc & progressrcv )
1216 std::list<RepoInfo> repos = knownRepositories();
1217 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1221 for(RepoInfo::urls_const_iterator urlit = (*it).baseUrlsBegin();
1222 urlit != (*it).baseUrlsEnd();
1225 if ((*urlit).asString(urlview) == url.asString(urlview))
1230 info.setAlias(info.alias());
1231 info.setBaseUrl(url);
1232 ZYPP_THROW(RepoNotFoundException(info));
1235 ////////////////////////////////////////////////////////////////////////////
1237 std::ostream & operator<<( std::ostream & str, const RepoManager & obj )
1239 return str << *obj._pimpl;
1242 /////////////////////////////////////////////////////////////////
1244 ///////////////////////////////////////////////////////////////////