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/cache/SolvStore.h"
32 #include "zypp/repo/cached/RepoImpl.h"
33 #include "zypp/media/MediaManager.h"
34 #include "zypp/MediaSetAccess.h"
35 #include "zypp/ExternalProgram.h"
36 #include "zypp/ManagedFile.h"
38 #include "zypp/parser/RepoFileReader.h"
39 #include "zypp/repo/yum/Downloader.h"
40 #include "zypp/parser/yum/RepoParser.h"
41 //#include "zypp/parser/plaindir/RepoParser.h"
42 #include "zypp/repo/susetags/Downloader.h"
43 #include "zypp/parser/susetags/RepoParser.h"
45 #include "zypp/ZYppCallbacks.h"
48 #include "satsolver/pool.h"
49 #include "satsolver/repo.h"
50 #include "satsolver/repo_solv.h"
54 using namespace zypp::repo;
55 using namespace zypp::filesystem;
57 using namespace zypp::repo;
59 ///////////////////////////////////////////////////////////////////
61 { /////////////////////////////////////////////////////////////////
63 ///////////////////////////////////////////////////////////////////
65 // CLASS NAME : RepoManagerOptions
67 ///////////////////////////////////////////////////////////////////
69 RepoManagerOptions::RepoManagerOptions()
71 repoCachePath = ZConfig::instance().repoCachePath();
72 repoRawCachePath = ZConfig::instance().repoMetadataPath();
73 knownReposPath = ZConfig::instance().knownReposPath();
76 ////////////////////////////////////////////////////////////////////////////
79 * \short Simple callback to collect the results
81 * Classes like RepoFileParser call the callback
82 * once per each repo in a file.
84 * Passing this functor as callback, you can collect
85 * all resuls at the end, without dealing with async
100 bool collect( const RepoInfo &repo )
102 //MIL << "here in collector: " << repo.alias() << endl;
103 repos.push_back(repo);
104 //MIL << "added: " << repo.alias() << endl;
111 ////////////////////////////////////////////////////////////////////////////
114 * \short Internal version of clean cache
116 * Takes an extra SolvStore reference, so we avoid internally
117 * having 2 SolvStores writing to the same database.
119 static void cleanCacheInternal( cache::SolvStore &store,
120 const RepoInfo &info,
121 const ProgressData::ReceiverFnc & progressrcv = ProgressData::ReceiverFnc() )
123 // ProgressData progress;
124 // callback::SendReport<ProgressReport> report;
125 // progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
126 // progress.name(str::form(_("Cleaning repository '%s' cache"), info.name().c_str()));
128 // if ( !store.isCached(info.alias()) )
131 // MIL << info.alias() << " cleaning cache..." << endl;
133 // CombinedProgressData subprogrcv(progress);
135 // store.cleanRepository(info.alias(), subprogrcv);
138 ////////////////////////////////////////////////////////////////////////////
141 * Reads RepoInfo's from a repo file.
143 * \param file pathname of the file to read.
145 static std::list<RepoInfo> repositories_in_file( const Pathname & file )
147 MIL << "repo file: " << file << endl;
148 RepoCollector collector;
149 parser::RepoFileReader parser( file, bind( &RepoCollector::collect, &collector, _1 ) );
150 return collector.repos;
153 ////////////////////////////////////////////////////////////////////////////
155 std::list<RepoInfo> readRepoFile(const Url & repo_file)
157 // no interface to download a specific file, using workaround:
158 //! \todo add MediaManager::provideFile(Url file_url) to easily access any file URLs? (no need for media access id or media_nr)
160 Pathname path(url.getPathName());
161 url.setPathName ("/");
162 MediaSetAccess access(url);
163 Pathname local = access.provideFile(path);
165 DBG << "reading repo file " << repo_file << ", local path: " << local << endl;
167 return repositories_in_file(local);
170 ////////////////////////////////////////////////////////////////////////////
173 * \short List of RepoInfo's from a directory
175 * Goes trough every file ending with ".repo" in a directory and adds all
176 * RepoInfo's contained in that file.
178 * \param dir pathname of the directory to read.
180 static std::list<RepoInfo> repositories_in_dir( const Pathname &dir )
182 MIL << "directory " << dir << endl;
183 list<RepoInfo> repos;
184 list<Pathname> entries;
185 if ( filesystem::readdir( entries, Pathname(dir), false ) != 0 )
186 ZYPP_THROW(Exception("failed to read directory"));
188 str::regex allowedRepoExt("^\\.repo(_[0-9]+)?$");
189 for ( list<Pathname>::const_iterator it = entries.begin(); it != entries.end(); ++it )
191 if (str::regex_match(it->extension(), allowedRepoExt))
193 list<RepoInfo> tmp = repositories_in_file( *it );
194 repos.insert( repos.end(), tmp.begin(), tmp.end() );
196 //std::copy( collector.repos.begin(), collector.repos.end(), std::back_inserter(repos));
197 //MIL << "ok" << endl;
203 ////////////////////////////////////////////////////////////////////////////
205 static void assert_alias( const RepoInfo &info )
207 if (info.alias().empty())
208 ZYPP_THROW(RepoNoAliasException());
211 ////////////////////////////////////////////////////////////////////////////
213 static void assert_urls( const RepoInfo &info )
215 if (info.baseUrlsEmpty())
216 ZYPP_THROW(RepoNoUrlException());
219 ////////////////////////////////////////////////////////////////////////////
222 * \short Calculates the raw cache path for a repository
224 static Pathname rawcache_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info )
227 return opt.repoRawCachePath + info.alias();
230 ///////////////////////////////////////////////////////////////////
232 // CLASS NAME : RepoManager::Impl
234 ///////////////////////////////////////////////////////////////////
237 * \short RepoManager implementation.
239 struct RepoManager::Impl
241 Impl( const RepoManagerOptions &opt )
252 RepoManagerOptions options;
254 map<string, RepoInfo> _repoinfos;
257 /** Offer default Impl. */
258 static shared_ptr<Impl> nullimpl()
260 static shared_ptr<Impl> _nullimpl( new Impl );
265 friend Impl * rwcowClone<Impl>( const Impl * rhs );
266 /** clone for RWCOW_pointer */
268 { return new Impl( *this ); }
271 ///////////////////////////////////////////////////////////////////
273 /** \relates RepoManager::Impl Stream output */
274 inline std::ostream & operator<<( std::ostream & str, const RepoManager::Impl & obj )
276 return str << "RepoManager::Impl";
279 ///////////////////////////////////////////////////////////////////
281 // CLASS NAME : RepoManager
283 ///////////////////////////////////////////////////////////////////
285 RepoManager::RepoManager( const RepoManagerOptions &opt )
286 : _pimpl( new Impl(opt) )
289 ////////////////////////////////////////////////////////////////////////////
291 RepoManager::~RepoManager()
294 ////////////////////////////////////////////////////////////////////////////
296 std::list<RepoInfo> RepoManager::knownRepositories() const
300 if ( PathInfo(_pimpl->options.knownReposPath).isExist() )
302 RepoInfoList repos = repositories_in_dir(_pimpl->options.knownReposPath);
303 for ( RepoInfoList::iterator it = repos.begin();
307 // set the metadata path for the repo
308 Pathname metadata_path = rawcache_path_for_repoinfo(_pimpl->options, (*it));
309 (*it).setMetadataPath(metadata_path);
314 return std::list<RepoInfo>();
319 ////////////////////////////////////////////////////////////////////////////
321 Pathname RepoManager::metadataPath( const RepoInfo &info ) const
323 return rawcache_path_for_repoinfo(_pimpl->options, info );
326 ////////////////////////////////////////////////////////////////////////////
328 RepoStatus RepoManager::metadataStatus( const RepoInfo &info ) const
330 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
331 RepoType repokind = info.type();
334 switch ( repokind.toEnum() )
336 case RepoType::NONE_e:
337 // unknown, probe the local metadata
338 repokind = probe(rawpath.asUrl());
344 switch ( repokind.toEnum() )
346 case RepoType::RPMMD_e :
348 status = RepoStatus( rawpath + "/repodata/repomd.xml");
352 case RepoType::YAST2_e :
354 // the order of RepoStatus && RepoStatus matters! (#304310)
355 status = RepoStatus( rawpath + "/content") && (RepoStatus( rawpath + "/media.1/media"));
359 case RepoType::RPMPLAINDIR_e :
361 if ( PathInfo(Pathname(rawpath + "/cookie")).isExist() )
362 status = RepoStatus( rawpath + "/cookie");
366 case RepoType::NONE_e :
367 // Return default RepoStatus in case of RepoType::NONE
368 // indicating it should be created?
369 // ZYPP_THROW(RepoUnknownTypeException());
375 void RepoManager::touchIndexFile(const RepoInfo & info)
377 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
379 RepoType repokind = info.type();
380 if ( repokind.toEnum() == RepoType::NONE_e )
381 // unknown, probe the local metadata
382 repokind = probe(rawpath.asUrl());
383 // if still unknown, just return
384 if (repokind == RepoType::NONE_e)
388 switch ( repokind.toEnum() )
390 case RepoType::RPMMD_e :
391 p = Pathname(rawpath + "/repodata/repomd.xml");
394 case RepoType::YAST2_e :
395 p = Pathname(rawpath + "/content");
398 case RepoType::RPMPLAINDIR_e :
399 p = Pathname(rawpath + "/cookie");
402 case RepoType::NONE_e :
407 // touch the file, ignore error (they are logged anyway)
408 filesystem::touch(p);
411 bool RepoManager::checkIfToRefreshMetadata( const RepoInfo &info,
413 RawMetadataRefreshPolicy policy )
417 RepoStatus oldstatus;
418 RepoStatus newstatus;
422 MIL << "Going to try to check whether refresh is needed for " << url << endl;
424 repo::RepoType repokind = info.type();
426 // if the type is unknown, try probing.
427 switch ( repokind.toEnum() )
429 case RepoType::NONE_e:
431 repokind = probe(url);
437 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
438 filesystem::assert_dir(rawpath);
439 oldstatus = metadataStatus(info);
441 // now we've got the old (cached) status, we can decide repo.refresh.delay
442 if (policy != RefreshForced)
444 // difference in seconds
445 double diff = difftime(
446 (Date::ValueType)Date::now(),
447 (Date::ValueType)oldstatus.timestamp()) / 60;
449 DBG << "oldstatus: " << (Date::ValueType)oldstatus.timestamp() << endl;
450 DBG << "current time: " << (Date::ValueType)Date::now() << endl;
451 DBG << "last refresh = " << diff << " minutes ago" << endl;
453 if (diff < ZConfig::instance().repo_refresh_delay())
455 MIL << "Repository '" << info.alias()
456 << "' has been refreshed less than repo.refresh.delay ("
457 << ZConfig::instance().repo_refresh_delay()
458 << ") minutes ago. Advising to skip refresh" << endl;
463 // create temp dir as sibling of rawpath
464 filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( rawpath ) );
466 if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
467 ( repokind.toEnum() == RepoType::YAST2_e ) )
469 MediaSetAccess media(url);
470 shared_ptr<repo::Downloader> downloader_ptr;
472 if ( repokind.toEnum() == RepoType::RPMMD_e )
473 downloader_ptr.reset(new yum::Downloader(info.path()));
475 downloader_ptr.reset( new susetags::Downloader(info.path()));
477 RepoStatus newstatus = downloader_ptr->status(media);
478 bool refresh = false;
479 if ( oldstatus.checksum() == newstatus.checksum() )
481 MIL << "repo has not changed" << endl;
482 if ( policy == RefreshForced )
484 MIL << "refresh set to forced" << endl;
490 MIL << "repo has changed, going to refresh" << endl;
495 touchIndexFile(info);
500 else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
502 RepoStatus newstatus = parser::plaindir::dirStatus(url.getPathName());
503 bool refresh = false;
504 if ( oldstatus.checksum() == newstatus.checksum() )
506 MIL << "repo has not changed" << endl;
507 if ( policy == RefreshForced )
509 MIL << "refresh set to forced" << endl;
515 MIL << "repo has changed, going to refresh" << endl;
520 touchIndexFile(info);
527 ZYPP_THROW(RepoUnknownTypeException());
530 catch ( const Exception &e )
533 ERR << "refresh check failed for " << url << endl;
537 return true; // default
540 void RepoManager::refreshMetadata( const RepoInfo &info,
541 RawMetadataRefreshPolicy policy,
542 const ProgressData::ReceiverFnc & progress )
547 // we will throw this later if no URL checks out fine
548 RepoException rexception(_("Valid metadata not found at specified URL(s)"));
550 // try urls one by one
551 for ( RepoInfo::urls_const_iterator it = info.baseUrlsBegin(); it != info.baseUrlsEnd(); ++it )
557 // check whether to refresh metadata
558 // if the check fails for this url, it throws, so another url will be checked
559 if (!checkIfToRefreshMetadata(info, url, policy))
562 MIL << "Going to refresh metadata from " << url << endl;
564 repo::RepoType repokind = info.type();
566 // if the type is unknown, try probing.
567 switch ( repokind.toEnum() )
569 case RepoType::NONE_e:
571 repokind = probe(*it);
577 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
578 filesystem::assert_dir(rawpath);
580 // create temp dir as sibling of rawpath
581 filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( rawpath ) );
583 if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
584 ( repokind.toEnum() == RepoType::YAST2_e ) )
586 MediaSetAccess media(url);
587 shared_ptr<repo::Downloader> downloader_ptr;
589 if ( repokind.toEnum() == RepoType::RPMMD_e )
590 downloader_ptr.reset(new yum::Downloader(info.path()));
592 downloader_ptr.reset( new susetags::Downloader(info.path()));
595 * Given a downloader, sets the other repos raw metadata
596 * path as cache paths for the fetcher, so if another
597 * repo has the same file, it will not download it
598 * but copy it from the other repository
600 std::list<RepoInfo> repos = knownRepositories();
601 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
605 downloader_ptr->addCachePath(rawcache_path_for_repoinfo( _pimpl->options, *it ));
608 downloader_ptr->download( media, tmpdir.path());
611 else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
613 RepoStatus newstatus = parser::plaindir::dirStatus(url.getPathName());
615 std::ofstream file(( tmpdir.path() + "/cookie").c_str());
617 ZYPP_THROW (Exception( "Can't open " + tmpdir.path().asString() + "/cookie" ) );
620 file << newstatus.checksum() << endl;
627 ZYPP_THROW(RepoUnknownTypeException());
630 // ok we have the metadata, now exchange
632 TmpDir oldmetadata( TmpDir::makeSibling( rawpath ) );
633 filesystem::rename( rawpath, oldmetadata.path() );
634 // move the just downloaded there
635 filesystem::rename( tmpdir.path(), rawpath );
639 catch ( const Exception &e )
642 ERR << "Trying another url..." << endl;
644 // remember the exception caught for the *first URL*
645 // if all other URLs fail, the rexception will be thrown with the
646 // cause of the problem of the first URL remembered
647 if (it == info.baseUrlsBegin())
648 rexception.remember(e);
651 ERR << "No more urls..." << endl;
652 ZYPP_THROW(rexception);
655 ////////////////////////////////////////////////////////////////////////////
657 void RepoManager::cleanMetadata( const RepoInfo &info,
658 const ProgressData::ReceiverFnc & progressfnc )
660 ProgressData progress(100);
661 progress.sendTo(progressfnc);
663 filesystem::recursive_rmdir(rawcache_path_for_repoinfo(_pimpl->options, info));
667 void RepoManager::buildCache( const RepoInfo &info,
668 CacheBuildPolicy policy,
669 const ProgressData::ReceiverFnc & progressrcv )
672 Pathname rawpath = rawcache_path_for_repoinfo(_pimpl->options, info);
674 Pathname base = _pimpl->options.repoCachePath + info.alias();
675 Pathname solvfile = base.extend(".solv");
677 //cache::SolvStore store(_pimpl->options.repoCachePath);
679 RepoStatus raw_metadata_status = metadataStatus(info);
680 if ( raw_metadata_status.empty() )
682 ZYPP_THROW(RepoMetadataException(info));
685 bool needs_cleaning = false;
686 if ( isCached( info ) )
688 MIL << info.alias() << " is already cached." << endl;
689 //data::RecordId id = store.lookupRepository(info.alias());
690 RepoStatus cache_status = cacheStatus(info);
692 if ( cache_status.checksum() == raw_metadata_status.checksum() )
694 MIL << info.alias() << " cache is up to date with metadata." << endl;
695 if ( policy == BuildIfNeeded ) {
699 MIL << info.alias() << " cache rebuild is forced" << endl;
703 needs_cleaning = true;
706 ProgressData progress(100);
707 callback::SendReport<ProgressReport> report;
708 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
709 progress.name(str::form(_("Building repository '%s' cache"), info.name().c_str()));
714 // Pathname name = _pimpl->options.repoCachePath;
715 // //data::RecordId id = store.lookupRepository(info.alias());
718 // name += os.str() + ".solv";
720 // cleanCacheInternal( store, info);
724 MIL << info.alias() << " building cache..." << endl;
725 //data::RecordId id = store.lookupOrAppendRepository(info.alias());
727 repo::RepoType repokind = info.type();
729 // if the type is unknown, try probing.
730 switch ( repokind.toEnum() )
732 case RepoType::NONE_e:
733 // unknown, probe the local metadata
734 repokind = probe(rawpath.asUrl());
740 MIL << "repo type is " << repokind << endl;
742 switch ( repokind.toEnum() )
744 case RepoType::RPMMD_e :
745 case RepoType::YAST2_e :
747 MIL << "Executing solv converter" << endl;
748 // Take care we unlink the solvfile on exception
749 ManagedFile guard( solvfile, filesystem::unlink );
751 string cmd( str::form( "/usr/bin/repo2solv.sh \"%s\" > '%s'", rawpath.c_str(), solvfile.c_str() ) );
752 ExternalProgram prog( cmd, ExternalProgram::Stderr_To_Stdout );
753 for ( string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() ) {
754 MIL << " " << output;
756 int ret = prog.close();
758 ZYPP_THROW(RepoUnknownTypeException());
761 guard.resetDispose();
765 ZYPP_THROW(Exception("Unhandled repostory type"));
769 switch ( repokind.toEnum() )
771 case RepoType::RPMMD_e :
774 CombinedProgressData subprogrcv( progress, 100);
775 parser::yum::RepoParser parser(id, store, parser::yum::RepoParserOpts(), subprogrcv);
776 parser.parse(rawpath);
780 case RepoType::YAST2_e :
783 CombinedProgressData subprogrcv( progress, 100);
784 parser::susetags::RepoParser parser(id, store, subprogrcv);
785 parser.parse(rawpath);
791 case RepoType::RPMPLAINDIR_e :
793 CombinedProgressData subprogrcv( progress, 100);
794 InputStream is(rawpath + "cookie");
796 getline( is.stream(), buffer);
798 parser::plaindir::RepoParser parser(id, store, subprogrcv);
799 parser.parse(url.getPathName());
804 ZYPP_THROW(RepoUnknownTypeException());
807 // update timestamp and checksum
808 //store.updateRepositoryStatus(id, raw_metadata_status);
809 setCacheStatus(info.alias(), raw_metadata_status);
810 MIL << "Commit cache.." << endl;
815 ////////////////////////////////////////////////////////////////////////////
817 repo::RepoType RepoManager::probe( const Url &url ) const
819 if ( url.getScheme() == "dir" && ! PathInfo( url.getPathName() ).isDir() )
821 // Handle non existing local directory in advance, as
822 // MediaSetAccess does not support it.
823 return repo::RepoType::NONE;
828 MediaSetAccess access(url);
829 if ( access.doesFileExist("/repodata/repomd.xml") )
830 return repo::RepoType::RPMMD;
831 if ( access.doesFileExist("/content") )
832 return repo::RepoType::YAST2;
834 // if it is a local url of type dir
835 if ( (! media::MediaManager::downloads(url)) && ( url.getScheme() == "dir" ) )
837 Pathname path = Pathname(url.getPathName());
838 if ( PathInfo(path).isDir() )
840 // allow empty dirs for now
841 return repo::RepoType::RPMPLAINDIR;
845 catch ( const media::MediaException &e )
848 RepoException enew("Error trying to read from " + url.asString());
852 catch ( const Exception &e )
855 Exception enew("Unknown error reading from " + url.asString());
860 return repo::RepoType::NONE;
863 ////////////////////////////////////////////////////////////////////////////
865 void RepoManager::cleanCache( const RepoInfo &info,
866 const ProgressData::ReceiverFnc & progressrcv )
868 Pathname name = _pimpl->options.repoCachePath;
869 name += info.alias() + ".solv";
873 ////////////////////////////////////////////////////////////////////////////
875 bool RepoManager::isCached( const RepoInfo &info ) const
877 Pathname name = _pimpl->options.repoCachePath;
878 return PathInfo(name + Pathname(info.alias()).extend(".solv")).isExist();
881 RepoStatus RepoManager::cacheStatus( const RepoInfo &info ) const
884 Pathname base = _pimpl->options.repoCachePath + info.alias();
885 Pathname cookiefile = base.extend(".cookie");
887 return RepoStatus::fromCookieFile(cookiefile);
890 void RepoManager::setCacheStatus( const string &alias, const RepoStatus &status )
892 Pathname base = _pimpl->options.repoCachePath + alias;
893 Pathname cookiefile = base.extend(".cookie");
895 status.saveToCookieFile(cookiefile);
898 void RepoManager::loadFromCache( const RepoInfo &info,
899 const ProgressData::ReceiverFnc & progressrcv )
902 sat::Pool satpool( sat::Pool::instance() );
903 string alias = info.alias();
905 Pathname solvfile = (_pimpl->options.repoCachePath + alias).extend(".solv");
907 if ( ! PathInfo(solvfile).isExist() )
908 ZYPP_THROW(RepoNotCachedException());
910 sat::Repo repo = satpool.addRepoSolv(solvfile, alias );
913 ////////////////////////////////////////////////////////////////////////////
916 * Generate a non existing filename in a directory, using a base
917 * name. For example if a directory contains 3 files
923 * If you try to generate a unique filename for this directory,
924 * based on "ruu" you will get "ruu", but if you use the base
925 * "foo" you will get "foo_1"
927 * \param dir Directory where the file needs to be unique
928 * \param basefilename string to base the filename on.
930 static Pathname generate_non_existing_name( const Pathname &dir,
931 const std::string &basefilename )
933 string final_filename = basefilename;
935 while ( PathInfo(dir + final_filename).isExist() )
937 final_filename = basefilename + "_" + str::numstring(counter);
940 return dir + Pathname(final_filename);
943 ////////////////////////////////////////////////////////////////////////////
946 * \short Generate a related filename from a repo info
948 * From a repo info, it will try to use the alias as a filename
949 * escaping it if necessary. Other fallbacks can be added to
950 * this function in case there is no way to use the alias
952 static std::string generate_filename( const RepoInfo &info )
956 std::string filename = info.alias();
957 // replace slashes with underscores
958 size_t pos = filename.find(fnd);
959 while(pos!=string::npos)
961 filename.replace(pos,fnd.length(),rep);
962 pos = filename.find(fnd,pos+rep.length());
964 filename = Pathname(filename).extend(".repo").asString();
965 MIL << "generating filename for repo [" << info.alias() << "] : '" << filename << "'" << endl;
970 ////////////////////////////////////////////////////////////////////////////
972 void RepoManager::addRepository( const RepoInfo &info,
973 const ProgressData::ReceiverFnc & progressrcv )
977 ProgressData progress(100);
978 callback::SendReport<ProgressReport> report;
979 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
980 progress.name(str::form(_("Adding repository '%s'"), info.name().c_str()));
983 std::list<RepoInfo> repos = knownRepositories();
984 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
988 if ( info.alias() == (*it).alias() )
989 ZYPP_THROW(RepoAlreadyExistsException(info.alias()));
992 RepoInfo tosave = info;
994 // check the first url for now
995 if ( ZConfig::instance().repo_add_probe()
996 || ( tosave.type() == RepoType::NONE && tosave.enabled()) )
998 DBG << "unknown repository type, probing" << endl;
1000 RepoType probedtype;
1001 probedtype = probe(*tosave.baseUrlsBegin());
1002 if ( tosave.baseUrlsSize() > 0 )
1004 if ( probedtype == RepoType::NONE )
1005 ZYPP_THROW(RepoUnknownTypeException());
1007 tosave.setType(probedtype);
1013 // assert the directory exists
1014 filesystem::assert_dir(_pimpl->options.knownReposPath);
1016 Pathname repofile = generate_non_existing_name(_pimpl->options.knownReposPath,
1017 generate_filename(tosave));
1018 // now we have a filename that does not exists
1019 MIL << "Saving repo in " << repofile << endl;
1021 std::ofstream file(repofile.c_str());
1023 ZYPP_THROW (Exception( "Can't open " + repofile.asString() ) );
1026 tosave.dumpRepoOn(file);
1028 MIL << "done" << endl;
1031 void RepoManager::addRepositories( const Url &url,
1032 const ProgressData::ReceiverFnc & progressrcv )
1034 std::list<RepoInfo> knownrepos = knownRepositories();
1035 std::list<RepoInfo> repos = readRepoFile(url);
1036 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1040 // look if the alias is in the known repos.
1041 for ( std::list<RepoInfo>::const_iterator kit = knownrepos.begin();
1042 kit != knownrepos.end();
1045 if ( (*it).alias() == (*kit).alias() )
1047 ERR << "To be added repo " << (*it).alias() << " conflicts with existing repo " << (*kit).alias() << endl;
1048 ZYPP_THROW(RepoAlreadyExistsException((*it).alias()));
1053 string filename = Pathname(url.getPathName()).basename();
1055 if ( filename == Pathname() )
1056 ZYPP_THROW(RepoException("Invalid repo file name at " + url.asString() ));
1058 // assert the directory exists
1059 filesystem::assert_dir(_pimpl->options.knownReposPath);
1061 Pathname repofile = generate_non_existing_name(_pimpl->options.knownReposPath, filename);
1062 // now we have a filename that does not exists
1063 MIL << "Saving " << repos.size() << " repo" << ( repos.size() ? "s" : "" ) << " in " << repofile << endl;
1065 std::ofstream file(repofile.c_str());
1067 ZYPP_THROW (Exception( "Can't open " + repofile.asString() ) );
1070 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1074 MIL << "Saving " << (*it).alias() << endl;
1075 (*it).dumpRepoOn(file);
1077 MIL << "done" << endl;
1080 ////////////////////////////////////////////////////////////////////////////
1082 void RepoManager::removeRepository( const RepoInfo & info,
1083 const ProgressData::ReceiverFnc & progressrcv)
1085 ProgressData progress;
1086 callback::SendReport<ProgressReport> report;
1087 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1088 progress.name(str::form(_("Removing repository '%s'"), info.name().c_str()));
1090 MIL << "Going to delete repo " << info.alias() << endl;
1092 std::list<RepoInfo> repos = knownRepositories();
1093 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1097 // they can be the same only if the provided is empty, that means
1098 // the provided repo has no alias
1100 if ( (!info.alias().empty()) && ( info.alias() != (*it).alias() ) )
1103 // TODO match by url
1105 // we have a matcing repository, now we need to know
1106 // where it does come from.
1107 RepoInfo todelete = *it;
1108 if (todelete.filepath().empty())
1110 ZYPP_THROW(RepoException("Can't figure where the repo is stored"));
1114 // figure how many repos are there in the file:
1115 std::list<RepoInfo> filerepos = repositories_in_file(todelete.filepath());
1116 if ( (filerepos.size() == 1) && ( filerepos.front().alias() == todelete.alias() ) )
1118 // easy, only this one, just delete the file
1119 if ( filesystem::unlink(todelete.filepath()) != 0 )
1121 ZYPP_THROW(RepoException("Can't delete " + todelete.filepath().asString()));
1123 MIL << todelete.alias() << " sucessfully deleted." << endl;
1127 // there are more repos in the same file
1128 // write them back except the deleted one.
1130 //std::ofstream file(tmp.path().c_str());
1132 // assert the directory exists
1133 filesystem::assert_dir(todelete.filepath().dirname());
1135 std::ofstream file(todelete.filepath().c_str());
1137 //ZYPP_THROW (Exception( "Can't open " + tmp.path().asString() ) );
1138 ZYPP_THROW (Exception( "Can't open " + todelete.filepath().asString() ) );
1140 for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1141 fit != filerepos.end();
1144 if ( (*fit).alias() != todelete.alias() )
1145 (*fit).dumpRepoOn(file);
1149 CombinedProgressData subprogrcv(progress, 70);
1150 CombinedProgressData cleansubprogrcv(progress, 30);
1151 // now delete it from cache
1152 if ( isCached(todelete) )
1153 cleanCache( todelete, subprogrcv);
1154 // now delete metadata (#301037)
1155 cleanMetadata( todelete, cleansubprogrcv);
1156 MIL << todelete.alias() << " sucessfully deleted." << endl;
1158 } // else filepath is empty
1161 // should not be reached on a sucess workflow
1162 ZYPP_THROW(RepoNotFoundException(info));
1165 ////////////////////////////////////////////////////////////////////////////
1167 void RepoManager::modifyRepository( const std::string &alias,
1168 const RepoInfo & newinfo,
1169 const ProgressData::ReceiverFnc & progressrcv )
1171 RepoInfo toedit = getRepositoryInfo(alias);
1173 if (toedit.filepath().empty())
1175 ZYPP_THROW(RepoException("Can't figure where the repo is stored"));
1179 // figure how many repos are there in the file:
1180 std::list<RepoInfo> filerepos = repositories_in_file(toedit.filepath());
1182 // there are more repos in the same file
1183 // write them back except the deleted one.
1185 //std::ofstream file(tmp.path().c_str());
1187 // assert the directory exists
1188 filesystem::assert_dir(toedit.filepath().dirname());
1190 std::ofstream file(toedit.filepath().c_str());
1192 //ZYPP_THROW (Exception( "Can't open " + tmp.path().asString() ) );
1193 ZYPP_THROW (Exception( "Can't open " + toedit.filepath().asString() ) );
1195 for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1196 fit != filerepos.end();
1199 // if the alias is different, dump the original
1200 // if it is the same, dump the provided one
1201 if ( (*fit).alias() != toedit.alias() )
1202 (*fit).dumpRepoOn(file);
1204 newinfo.dumpRepoOn(file);
1209 ////////////////////////////////////////////////////////////////////////////
1211 RepoInfo RepoManager::getRepositoryInfo( const std::string &alias,
1212 const ProgressData::ReceiverFnc & progressrcv )
1214 std::list<RepoInfo> repos = knownRepositories();
1215 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1219 if ( (*it).alias() == alias )
1223 info.setAlias(info.alias());
1224 ZYPP_THROW(RepoNotFoundException(info));
1227 ////////////////////////////////////////////////////////////////////////////
1229 RepoInfo RepoManager::getRepositoryInfo( const Url & url,
1230 const url::ViewOption & urlview,
1231 const ProgressData::ReceiverFnc & progressrcv )
1233 std::list<RepoInfo> repos = knownRepositories();
1234 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1238 for(RepoInfo::urls_const_iterator urlit = (*it).baseUrlsBegin();
1239 urlit != (*it).baseUrlsEnd();
1242 if ((*urlit).asString(urlview) == url.asString(urlview))
1247 info.setAlias(info.alias());
1248 info.setBaseUrl(url);
1249 ZYPP_THROW(RepoNotFoundException(info));
1252 ////////////////////////////////////////////////////////////////////////////
1254 std::ostream & operator<<( std::ostream & str, const RepoManager & obj )
1256 return str << *obj._pimpl;
1259 /////////////////////////////////////////////////////////////////
1261 ///////////////////////////////////////////////////////////////////