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 repoPackagesCachePath = ZConfig::instance().repoPackagesPath();
71 knownReposPath = ZConfig::instance().knownReposPath();
72 probe = ZConfig::instance().repo_add_probe();
75 ////////////////////////////////////////////////////////////////////////////
78 * \short Simple callback to collect the results
80 * Classes like RepoFileParser call the callback
81 * once per each repo in a file.
83 * Passing this functor as callback, you can collect
84 * all resuls at the end, without dealing with async
95 bool collect( const RepoInfo &repo )
97 repos.push_back(repo);
104 ////////////////////////////////////////////////////////////////////////////
107 * Reads RepoInfo's from a repo file.
109 * \param file pathname of the file to read.
111 static std::list<RepoInfo> repositories_in_file( const Pathname & file )
113 MIL << "repo file: " << file << endl;
114 RepoCollector collector;
115 parser::RepoFileReader parser( file, bind( &RepoCollector::collect, &collector, _1 ) );
116 return collector.repos;
119 ////////////////////////////////////////////////////////////////////////////
121 std::list<RepoInfo> readRepoFile(const Url & repo_file)
123 // no interface to download a specific file, using workaround:
124 //! \todo add MediaManager::provideFile(Url file_url) to easily access any file URLs? (no need for media access id or media_nr)
126 Pathname path(url.getPathName());
127 url.setPathName ("/");
128 MediaSetAccess access(url);
129 Pathname local = access.provideFile(path);
131 DBG << "reading repo file " << repo_file << ", local path: " << local << endl;
133 return repositories_in_file(local);
136 ////////////////////////////////////////////////////////////////////////////
139 * \short List of RepoInfo's from a directory
141 * Goes trough every file ending with ".repo" in a directory and adds all
142 * RepoInfo's contained in that file.
144 * \param dir pathname of the directory to read.
146 static std::list<RepoInfo> repositories_in_dir( const Pathname &dir )
148 MIL << "directory " << dir << endl;
149 list<RepoInfo> repos;
150 list<Pathname> entries;
151 if ( filesystem::readdir( entries, Pathname(dir), false ) != 0 )
152 ZYPP_THROW(Exception("failed to read directory"));
154 str::regex allowedRepoExt("^\\.repo(_[0-9]+)?$");
155 for ( list<Pathname>::const_iterator it = entries.begin(); it != entries.end(); ++it )
157 if (str::regex_match(it->extension(), allowedRepoExt))
159 list<RepoInfo> tmp = repositories_in_file( *it );
160 repos.insert( repos.end(), tmp.begin(), tmp.end() );
162 //std::copy( collector.repos.begin(), collector.repos.end(), std::back_inserter(repos));
163 //MIL << "ok" << endl;
169 ////////////////////////////////////////////////////////////////////////////
171 static void assert_alias( const RepoInfo &info )
173 if (info.alias().empty())
174 ZYPP_THROW(RepoNoAliasException());
177 ////////////////////////////////////////////////////////////////////////////
179 static void assert_urls( const RepoInfo &info )
181 if (info.baseUrlsEmpty())
182 ZYPP_THROW(RepoNoUrlException());
185 ////////////////////////////////////////////////////////////////////////////
188 * \short Calculates the raw cache path for a repository
190 static Pathname rawcache_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info )
193 return opt.repoRawCachePath / info.escaped_alias();
197 * \short Calculates the packages cache path for a repository
199 static Pathname packagescache_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info )
202 return opt.repoPackagesCachePath / info.escaped_alias();
205 ///////////////////////////////////////////////////////////////////
207 // CLASS NAME : RepoManager::Impl
209 ///////////////////////////////////////////////////////////////////
212 * \short RepoManager implementation.
214 struct RepoManager::Impl
216 Impl( const RepoManagerOptions &opt )
227 RepoManagerOptions options;
229 map<string, RepoInfo> _repoinfos;
232 /** Offer default Impl. */
233 static shared_ptr<Impl> nullimpl()
235 static shared_ptr<Impl> _nullimpl( new Impl );
240 friend Impl * rwcowClone<Impl>( const Impl * rhs );
241 /** clone for RWCOW_pointer */
243 { return new Impl( *this ); }
246 ///////////////////////////////////////////////////////////////////
248 /** \relates RepoManager::Impl Stream output */
249 inline std::ostream & operator<<( std::ostream & str, const RepoManager::Impl & obj )
251 return str << "RepoManager::Impl";
254 ///////////////////////////////////////////////////////////////////
256 // CLASS NAME : RepoManager
258 ///////////////////////////////////////////////////////////////////
260 RepoManager::RepoManager( const RepoManagerOptions &opt )
261 : _pimpl( new Impl(opt) )
264 ////////////////////////////////////////////////////////////////////////////
266 RepoManager::~RepoManager()
269 ////////////////////////////////////////////////////////////////////////////
271 std::list<RepoInfo> RepoManager::knownRepositories() const
275 if ( PathInfo(_pimpl->options.knownReposPath).isExist() )
277 RepoInfoList repos = repositories_in_dir(_pimpl->options.knownReposPath);
278 for ( RepoInfoList::iterator it = repos.begin();
282 // set the metadata path for the repo
283 Pathname metadata_path = rawcache_path_for_repoinfo(_pimpl->options, (*it));
284 (*it).setMetadataPath(metadata_path);
286 // set the downloaded packages path for the repo
287 Pathname packages_path = packagescache_path_for_repoinfo(_pimpl->options, (*it));
288 (*it).setPackagesPath(packages_path);
293 return std::list<RepoInfo>();
298 ////////////////////////////////////////////////////////////////////////////
300 Pathname RepoManager::metadataPath( const RepoInfo &info ) const
302 return rawcache_path_for_repoinfo(_pimpl->options, info );
305 ////////////////////////////////////////////////////////////////////////////
307 RepoStatus RepoManager::metadataStatus( const RepoInfo &info ) const
309 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
310 RepoType repokind = info.type();
313 switch ( repokind.toEnum() )
315 case RepoType::NONE_e:
316 // unknown, probe the local metadata
317 repokind = probe(rawpath.asUrl());
323 switch ( repokind.toEnum() )
325 case RepoType::RPMMD_e :
327 status = RepoStatus( rawpath + "/repodata/repomd.xml");
331 case RepoType::YAST2_e :
333 status = RepoStatus( rawpath + "/content") && (RepoStatus( rawpath + "/media.1/media"));
337 case RepoType::RPMPLAINDIR_e :
339 if ( PathInfo(Pathname(rawpath + "/cookie")).isExist() )
340 status = RepoStatus( rawpath + "/cookie");
344 case RepoType::NONE_e :
345 // Return default RepoStatus in case of RepoType::NONE
346 // indicating it should be created?
347 // ZYPP_THROW(RepoUnknownTypeException());
353 void RepoManager::touchIndexFile(const RepoInfo & info)
355 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
357 RepoType repokind = info.type();
358 if ( repokind.toEnum() == RepoType::NONE_e )
359 // unknown, probe the local metadata
360 repokind = probe(rawpath.asUrl());
361 // if still unknown, just return
362 if (repokind == RepoType::NONE_e)
366 switch ( repokind.toEnum() )
368 case RepoType::RPMMD_e :
369 p = Pathname(rawpath + "/repodata/repomd.xml");
372 case RepoType::YAST2_e :
373 p = Pathname(rawpath + "/content");
376 case RepoType::RPMPLAINDIR_e :
377 p = Pathname(rawpath + "/cookie");
380 case RepoType::NONE_e :
385 // touch the file, ignore error (they are logged anyway)
386 filesystem::touch(p);
389 bool RepoManager::checkIfToRefreshMetadata( const RepoInfo &info,
391 RawMetadataRefreshPolicy policy )
395 RepoStatus oldstatus;
396 RepoStatus newstatus;
400 MIL << "Going to try to check whether refresh is needed for " << url << endl;
402 repo::RepoType repokind = info.type();
404 // if the type is unknown, try probing.
405 switch ( repokind.toEnum() )
407 case RepoType::NONE_e:
409 repokind = probe(url);
415 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
416 filesystem::assert_dir(rawpath);
417 oldstatus = metadataStatus(info);
419 // now we've got the old (cached) status, we can decide repo.refresh.delay
420 if (policy != RefreshForced)
422 // difference in seconds
423 double diff = difftime(
424 (Date::ValueType)Date::now(),
425 (Date::ValueType)oldstatus.timestamp()) / 60;
427 DBG << "oldstatus: " << (Date::ValueType)oldstatus.timestamp() << endl;
428 DBG << "current time: " << (Date::ValueType)Date::now() << endl;
429 DBG << "last refresh = " << diff << " minutes ago" << endl;
431 if (diff < ZConfig::instance().repo_refresh_delay())
433 MIL << "Repository '" << info.alias()
434 << "' has been refreshed less than repo.refresh.delay ("
435 << ZConfig::instance().repo_refresh_delay()
436 << ") minutes ago. Advising to skip refresh" << endl;
441 // create temp dir as sibling of rawpath
442 filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( rawpath ) );
444 if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
445 ( repokind.toEnum() == RepoType::YAST2_e ) )
447 MediaSetAccess media(url);
448 shared_ptr<repo::Downloader> downloader_ptr;
450 if ( repokind.toEnum() == RepoType::RPMMD_e )
451 downloader_ptr.reset(new yum::Downloader(info.path()));
453 downloader_ptr.reset( new susetags::Downloader(info.path()));
455 RepoStatus newstatus = downloader_ptr->status(media);
456 bool refresh = false;
457 if ( oldstatus.checksum() == newstatus.checksum() )
459 MIL << "repo has not changed" << endl;
460 if ( policy == RefreshForced )
462 MIL << "refresh set to forced" << endl;
468 MIL << "repo has changed, going to refresh" << endl;
473 touchIndexFile(info);
478 else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
480 RepoStatus newstatus = parser::plaindir::dirStatus(url.getPathName());
481 bool refresh = false;
482 if ( oldstatus.checksum() == newstatus.checksum() )
484 MIL << "repo has not changed" << endl;
485 if ( policy == RefreshForced )
487 MIL << "refresh set to forced" << endl;
493 MIL << "repo has changed, going to refresh" << endl;
498 touchIndexFile(info);
505 ZYPP_THROW(RepoUnknownTypeException());
508 catch ( const Exception &e )
511 ERR << "refresh check failed for " << url << endl;
515 return true; // default
518 void RepoManager::refreshMetadata( const RepoInfo &info,
519 RawMetadataRefreshPolicy policy,
520 const ProgressData::ReceiverFnc & progress )
525 // we will throw this later if no URL checks out fine
526 RepoException rexception(_("Valid metadata not found at specified URL(s)"));
528 // try urls one by one
529 for ( RepoInfo::urls_const_iterator it = info.baseUrlsBegin(); it != info.baseUrlsEnd(); ++it )
535 // check whether to refresh metadata
536 // if the check fails for this url, it throws, so another url will be checked
537 if (!checkIfToRefreshMetadata(info, url, policy))
540 MIL << "Going to refresh metadata from " << url << endl;
542 repo::RepoType repokind = info.type();
544 // if the type is unknown, try probing.
545 switch ( repokind.toEnum() )
547 case RepoType::NONE_e:
549 repokind = probe(*it);
555 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
556 filesystem::assert_dir(rawpath);
558 // create temp dir as sibling of rawpath
559 filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( rawpath ) );
561 if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
562 ( repokind.toEnum() == RepoType::YAST2_e ) )
564 MediaSetAccess media(url);
565 shared_ptr<repo::Downloader> downloader_ptr;
567 if ( repokind.toEnum() == RepoType::RPMMD_e )
568 downloader_ptr.reset(new yum::Downloader(info.path()));
570 downloader_ptr.reset( new susetags::Downloader(info.path()));
573 * Given a downloader, sets the other repos raw metadata
574 * path as cache paths for the fetcher, so if another
575 * repo has the same file, it will not download it
576 * but copy it from the other repository
578 std::list<RepoInfo> repos = knownRepositories();
579 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
583 Pathname cachepath(rawcache_path_for_repoinfo( _pimpl->options, *it ));
584 if ( PathInfo(cachepath).isExist() )
585 downloader_ptr->addCachePath(cachepath);
588 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;
607 ZYPP_THROW(RepoUnknownTypeException());
610 // ok we have the metadata, now exchange
613 TmpDir oldmetadata( TmpDir::makeSibling( rawpath ) );
614 filesystem::rename( rawpath, oldmetadata.path() );
615 // move the just downloaded there
616 filesystem::rename( tmpdir.path(), rawpath );
621 catch ( const Exception &e )
624 ERR << "Trying another url..." << endl;
626 // remember the exception caught for the *first URL*
627 // if all other URLs fail, the rexception will be thrown with the
628 // cause of the problem of the first URL remembered
629 if (it == info.baseUrlsBegin())
630 rexception.remember(e);
633 ERR << "No more urls..." << endl;
634 ZYPP_THROW(rexception);
637 ////////////////////////////////////////////////////////////////////////////
639 void RepoManager::cleanMetadata( const RepoInfo &info,
640 const ProgressData::ReceiverFnc & progressfnc )
642 ProgressData progress(100);
643 progress.sendTo(progressfnc);
645 filesystem::recursive_rmdir(rawcache_path_for_repoinfo(_pimpl->options, info));
649 void RepoManager::cleanPackages( const RepoInfo &info,
650 const ProgressData::ReceiverFnc & progressfnc )
652 ProgressData progress(100);
653 progress.sendTo(progressfnc);
655 filesystem::recursive_rmdir(packagescache_path_for_repoinfo(_pimpl->options, info));
659 void RepoManager::buildCache( const RepoInfo &info,
660 CacheBuildPolicy policy,
661 const ProgressData::ReceiverFnc & progressrcv )
664 Pathname rawpath = rawcache_path_for_repoinfo(_pimpl->options, info);
666 Pathname base = _pimpl->options.repoCachePath + info.escaped_alias();
667 Pathname solvfile = base.extend(".solv");
670 RepoStatus raw_metadata_status = metadataStatus(info);
671 if ( raw_metadata_status.empty() )
673 /* if there is no cache at this point, we refresh the raw
674 in case this is the first time - if it's !autorefresh,
675 we may still refresh */
676 refreshMetadata(info, RefreshIfNeeded, progressrcv );
677 raw_metadata_status = metadataStatus(info);
680 bool needs_cleaning = false;
681 if ( isCached( info ) )
683 MIL << info.alias() << " is already cached." << endl;
684 //data::RecordId id = store.lookupRepository(info.alias());
685 RepoStatus cache_status = cacheStatus(info);
687 if ( cache_status.checksum() == raw_metadata_status.checksum() )
689 MIL << info.alias() << " cache is up to date with metadata." << endl;
690 if ( policy == BuildIfNeeded ) {
694 MIL << info.alias() << " cache rebuild is forced" << endl;
698 needs_cleaning = true;
701 ProgressData progress(100);
702 callback::SendReport<ProgressReport> report;
703 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
704 progress.name(str::form(_("Building repository '%s' cache"), info.name().c_str()));
712 MIL << info.alias() << " building cache..." << endl;
714 repo::RepoType repokind = info.type();
716 // if the type is unknown, try probing.
717 switch ( repokind.toEnum() )
719 case RepoType::NONE_e:
720 // unknown, probe the local metadata
721 repokind = probe(rawpath.asUrl());
727 MIL << "repo type is " << repokind << endl;
729 switch ( repokind.toEnum() )
731 case RepoType::RPMMD_e :
732 case RepoType::YAST2_e :
734 // Take care we unlink the solvfile on exception
735 ManagedFile guard( solvfile, filesystem::unlink );
738 cmd << str::form( "repo2solv.sh \"%s\" > \"%s\"", rawpath.c_str(), solvfile.c_str() );
740 MIL << "Executing: " << cmd.str() << endl;
741 ExternalProgram prog( cmd.str(), ExternalProgram::Stderr_To_Stdout );
744 for ( string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() ) {
745 WAR << " " << output;
746 cmd << " " << output;
749 int ret = prog.close();
752 RepoException ex(str::form("Failed to cache repo (%d).", ret));
753 ex.remember( cmd.str() );
758 guard.resetDispose();
762 ZYPP_THROW(RepoUnknownTypeException("Unhandled repository type"));
766 switch ( repokind.toEnum() )
768 case RepoType::RPMMD_e :
771 CombinedProgressData subprogrcv( progress, 100);
772 parser::yum::RepoParser parser(id, store, parser::yum::RepoParserOpts(), subprogrcv);
773 parser.parse(rawpath);
777 case RepoType::YAST2_e :
780 CombinedProgressData subprogrcv( progress, 100);
781 parser::susetags::RepoParser parser(id, store, subprogrcv);
782 parser.parse(rawpath);
788 case RepoType::RPMPLAINDIR_e :
790 CombinedProgressData subprogrcv( progress, 100);
791 InputStream is(rawpath + "cookie");
793 getline( is.stream(), buffer);
795 parser::plaindir::RepoParser parser(id, store, subprogrcv);
796 parser.parse(url.getPathName());
801 ZYPP_THROW(RepoUnknownTypeException());
804 // update timestamp and checksum
805 //store.updateRepositoryStatus(id, raw_metadata_status);
806 setCacheStatus(info.escaped_alias(), raw_metadata_status);
807 MIL << "Commit cache.." << endl;
812 ////////////////////////////////////////////////////////////////////////////
814 repo::RepoType RepoManager::probe( const Url &url ) const
816 if ( url.getScheme() == "dir" && ! PathInfo( url.getPathName() ).isDir() )
818 // Handle non existing local directory in advance, as
819 // MediaSetAccess does not support it.
820 return repo::RepoType::NONE;
825 MediaSetAccess access(url);
826 if ( access.doesFileExist("/repodata/repomd.xml") )
827 return repo::RepoType::RPMMD;
828 if ( access.doesFileExist("/content") )
829 return repo::RepoType::YAST2;
831 // if it is a local url of type dir
832 if ( (! media::MediaManager::downloads(url)) && ( url.getScheme() == "dir" ) )
834 Pathname path = Pathname(url.getPathName());
835 if ( PathInfo(path).isDir() )
837 // allow empty dirs for now
838 return repo::RepoType::RPMPLAINDIR;
842 catch ( const media::MediaException &e )
845 RepoException enew("Error trying to read from " + url.asString());
849 catch ( const Exception &e )
852 Exception enew("Unknown error reading from " + url.asString());
857 return repo::RepoType::NONE;
860 ////////////////////////////////////////////////////////////////////////////
862 void RepoManager::cleanCache( const RepoInfo &info,
863 const ProgressData::ReceiverFnc & progressrcv )
865 ProgressData progress(100);
866 progress.sendTo(progressrcv);
869 unlink (_pimpl->options.repoCachePath / (info.escaped_alias() + ".solv"));
871 unlink (_pimpl->options.repoCachePath / (info.escaped_alias() + ".cookie"));
876 void RepoManager::cleanTargetCache(const ProgressData::ReceiverFnc & progressrcv)
878 unlink (_pimpl->options.repoCachePath / (sat::Pool::systemRepoName() + ".solv"));
879 unlink (_pimpl->options.repoCachePath / (sat::Pool::systemRepoName() + ".cookie"));
882 ////////////////////////////////////////////////////////////////////////////
884 bool RepoManager::isCached( const RepoInfo &info ) const
886 Pathname name = _pimpl->options.repoCachePath;
887 return PathInfo(name + Pathname(info.escaped_alias()).extend(".solv")).isExist();
890 RepoStatus RepoManager::cacheStatus( const RepoInfo &info ) const
893 Pathname base = _pimpl->options.repoCachePath + info.escaped_alias();
894 Pathname cookiefile = base.extend(".cookie");
896 return RepoStatus::fromCookieFile(cookiefile);
899 void RepoManager::setCacheStatus( const string &alias, const RepoStatus &status )
901 Pathname base = _pimpl->options.repoCachePath + alias;
902 Pathname cookiefile = base.extend(".cookie");
904 status.saveToCookieFile(cookiefile);
907 void RepoManager::loadFromCache( const RepoInfo & info,
908 const ProgressData::ReceiverFnc & progressrcv )
911 string alias = info.escaped_alias();
912 Pathname solvfile = (_pimpl->options.repoCachePath / alias).extend(".solv");
914 if ( ! PathInfo(solvfile).isExist() )
915 ZYPP_THROW(RepoNotCachedException());
919 sat::Pool::instance().addRepoSolv( solvfile, info );
921 catch ( const Exception & exp )
924 MIL << "Try to handle exception by rebuilding the solv-file" << endl;
925 cleanCache( info, progressrcv );
926 buildCache( info, BuildIfNeeded, progressrcv );
928 sat::Pool::instance().addRepoSolv( solvfile, info );
932 ////////////////////////////////////////////////////////////////////////////
935 * Generate a non existing filename in a directory, using a base
936 * name. For example if a directory contains 3 files
942 * If you try to generate a unique filename for this directory,
943 * based on "ruu" you will get "ruu", but if you use the base
944 * "foo" you will get "foo_1"
946 * \param dir Directory where the file needs to be unique
947 * \param basefilename string to base the filename on.
949 static Pathname generate_non_existing_name( const Pathname &dir,
950 const std::string &basefilename )
952 string final_filename = basefilename;
954 while ( PathInfo(dir + final_filename).isExist() )
956 final_filename = basefilename + "_" + str::numstring(counter);
959 return dir + Pathname(final_filename);
962 ////////////////////////////////////////////////////////////////////////////
965 * \short Generate a related filename from a repo info
967 * From a repo info, it will try to use the alias as a filename
968 * escaping it if necessary. Other fallbacks can be added to
969 * this function in case there is no way to use the alias
971 static std::string generate_filename( const RepoInfo &info )
975 std::string filename = info.alias();
976 // replace slashes with underscores
977 size_t pos = filename.find(fnd);
978 while(pos!=string::npos)
980 filename.replace(pos,fnd.length(),rep);
981 pos = filename.find(fnd,pos+rep.length());
983 filename = Pathname(filename).extend(".repo").asString();
984 MIL << "generating filename for repo [" << info.alias() << "] : '" << filename << "'" << endl;
989 ////////////////////////////////////////////////////////////////////////////
991 void RepoManager::addRepository( const RepoInfo &info,
992 const ProgressData::ReceiverFnc & progressrcv )
996 ProgressData progress(100);
997 callback::SendReport<ProgressReport> report;
998 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
999 progress.name(str::form(_("Adding repository '%s'"), info.name().c_str()));
1002 std::list<RepoInfo> repos = knownRepositories();
1003 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1007 if ( info.alias() == (*it).alias() )
1008 ZYPP_THROW(RepoAlreadyExistsException(info.alias()));
1011 RepoInfo tosave = info;
1013 // check the first url for now
1014 if ( _pimpl->options.probe )
1016 DBG << "unknown repository type, probing" << endl;
1018 RepoType probedtype;
1019 probedtype = probe(*tosave.baseUrlsBegin());
1020 if ( tosave.baseUrlsSize() > 0 )
1022 if ( probedtype == RepoType::NONE )
1023 ZYPP_THROW(RepoUnknownTypeException());
1025 tosave.setType(probedtype);
1031 // assert the directory exists
1032 filesystem::assert_dir(_pimpl->options.knownReposPath);
1034 Pathname repofile = generate_non_existing_name(_pimpl->options.knownReposPath,
1035 generate_filename(tosave));
1036 // now we have a filename that does not exists
1037 MIL << "Saving repo in " << repofile << endl;
1039 std::ofstream file(repofile.c_str());
1041 ZYPP_THROW (Exception( "Can't open " + repofile.asString() ) );
1044 tosave.dumpRepoOn(file);
1046 MIL << "done" << endl;
1049 void RepoManager::addRepositories( const Url &url,
1050 const ProgressData::ReceiverFnc & progressrcv )
1052 std::list<RepoInfo> knownrepos = knownRepositories();
1053 std::list<RepoInfo> repos = readRepoFile(url);
1054 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1058 // look if the alias is in the known repos.
1059 for ( std::list<RepoInfo>::const_iterator kit = knownrepos.begin();
1060 kit != knownrepos.end();
1063 if ( (*it).alias() == (*kit).alias() )
1065 ERR << "To be added repo " << (*it).alias() << " conflicts with existing repo " << (*kit).alias() << endl;
1066 ZYPP_THROW(RepoAlreadyExistsException((*it).alias()));
1071 string filename = Pathname(url.getPathName()).basename();
1073 if ( filename == Pathname() )
1074 ZYPP_THROW(RepoException("Invalid repo file name at " + url.asString() ));
1076 // assert the directory exists
1077 filesystem::assert_dir(_pimpl->options.knownReposPath);
1079 Pathname repofile = generate_non_existing_name(_pimpl->options.knownReposPath, filename);
1080 // now we have a filename that does not exists
1081 MIL << "Saving " << repos.size() << " repo" << ( repos.size() ? "s" : "" ) << " in " << repofile << endl;
1083 std::ofstream file(repofile.c_str());
1085 ZYPP_THROW (Exception( "Can't open " + repofile.asString() ) );
1088 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1092 MIL << "Saving " << (*it).alias() << endl;
1093 (*it).dumpRepoOn(file);
1095 MIL << "done" << endl;
1098 ////////////////////////////////////////////////////////////////////////////
1100 void RepoManager::removeRepository( const RepoInfo & info,
1101 const ProgressData::ReceiverFnc & progressrcv)
1103 ProgressData progress;
1104 callback::SendReport<ProgressReport> report;
1105 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1106 progress.name(str::form(_("Removing repository '%s'"), info.name().c_str()));
1108 MIL << "Going to delete repo " << info.alias() << endl;
1110 std::list<RepoInfo> repos = knownRepositories();
1111 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1115 // they can be the same only if the provided is empty, that means
1116 // the provided repo has no alias
1118 if ( (!info.alias().empty()) && ( info.alias() != (*it).alias() ) )
1121 // TODO match by url
1123 // we have a matcing repository, now we need to know
1124 // where it does come from.
1125 RepoInfo todelete = *it;
1126 if (todelete.filepath().empty())
1128 ZYPP_THROW(RepoException("Can't figure where the repo is stored"));
1132 // figure how many repos are there in the file:
1133 std::list<RepoInfo> filerepos = repositories_in_file(todelete.filepath());
1134 if ( (filerepos.size() == 1) && ( filerepos.front().alias() == todelete.alias() ) )
1136 // easy, only this one, just delete the file
1137 if ( filesystem::unlink(todelete.filepath()) != 0 )
1139 ZYPP_THROW(RepoException("Can't delete " + todelete.filepath().asString()));
1141 MIL << todelete.alias() << " sucessfully deleted." << endl;
1145 // there are more repos in the same file
1146 // write them back except the deleted one.
1148 //std::ofstream file(tmp.path().c_str());
1150 // assert the directory exists
1151 filesystem::assert_dir(todelete.filepath().dirname());
1153 std::ofstream file(todelete.filepath().c_str());
1155 //ZYPP_THROW (Exception( "Can't open " + tmp.path().asString() ) );
1156 ZYPP_THROW (Exception( "Can't open " + todelete.filepath().asString() ) );
1158 for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1159 fit != filerepos.end();
1162 if ( (*fit).alias() != todelete.alias() )
1163 (*fit).dumpRepoOn(file);
1167 CombinedProgressData subprogrcv(progress, 70);
1168 CombinedProgressData cleansubprogrcv(progress, 30);
1169 // now delete it from cache
1170 if ( isCached(todelete) )
1171 cleanCache( todelete, subprogrcv);
1172 // now delete metadata (#301037)
1173 cleanMetadata( todelete, cleansubprogrcv);
1174 MIL << todelete.alias() << " sucessfully deleted." << endl;
1176 } // else filepath is empty
1179 // should not be reached on a sucess workflow
1180 ZYPP_THROW(RepoNotFoundException(info));
1183 ////////////////////////////////////////////////////////////////////////////
1185 void RepoManager::modifyRepository( const std::string &alias,
1186 const RepoInfo & newinfo,
1187 const ProgressData::ReceiverFnc & progressrcv )
1189 RepoInfo toedit = getRepositoryInfo(alias);
1191 // check if the new alias already exists when renaming the repo
1192 if (alias != newinfo.alias())
1194 std::list<RepoInfo> repos = knownRepositories();
1195 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1199 if ( newinfo.alias() == (*it).alias() )
1200 ZYPP_THROW(RepoAlreadyExistsException(newinfo.alias()));
1204 if (toedit.filepath().empty())
1206 ZYPP_THROW(RepoException("Can't figure where the repo is stored"));
1210 // figure how many repos are there in the file:
1211 std::list<RepoInfo> filerepos = repositories_in_file(toedit.filepath());
1213 // there are more repos in the same file
1214 // write them back except the deleted one.
1216 //std::ofstream file(tmp.path().c_str());
1218 // assert the directory exists
1219 filesystem::assert_dir(toedit.filepath().dirname());
1221 std::ofstream file(toedit.filepath().c_str());
1223 //ZYPP_THROW (Exception( "Can't open " + tmp.path().asString() ) );
1224 ZYPP_THROW (Exception( "Can't open " + toedit.filepath().asString() ) );
1226 for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1227 fit != filerepos.end();
1230 // if the alias is different, dump the original
1231 // if it is the same, dump the provided one
1232 if ( (*fit).alias() != toedit.alias() )
1233 (*fit).dumpRepoOn(file);
1235 newinfo.dumpRepoOn(file);
1240 ////////////////////////////////////////////////////////////////////////////
1242 RepoInfo RepoManager::getRepositoryInfo( const std::string &alias,
1243 const ProgressData::ReceiverFnc & progressrcv )
1245 std::list<RepoInfo> repos = knownRepositories();
1246 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1250 if ( (*it).alias() == alias )
1254 info.setAlias(info.alias());
1255 ZYPP_THROW(RepoNotFoundException(info));
1258 ////////////////////////////////////////////////////////////////////////////
1260 RepoInfo RepoManager::getRepositoryInfo( const Url & url,
1261 const url::ViewOption & urlview,
1262 const ProgressData::ReceiverFnc & progressrcv )
1264 std::list<RepoInfo> repos = knownRepositories();
1265 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1269 for(RepoInfo::urls_const_iterator urlit = (*it).baseUrlsBegin();
1270 urlit != (*it).baseUrlsEnd();
1273 if ((*urlit).asString(urlview) == url.asString(urlview))
1278 info.setAlias(info.alias());
1279 info.setBaseUrl(url);
1280 ZYPP_THROW(RepoNotFoundException(info));
1283 ////////////////////////////////////////////////////////////////////////////
1285 std::ostream & operator<<( std::ostream & str, const RepoManager & obj )
1287 return str << *obj._pimpl;
1290 /////////////////////////////////////////////////////////////////
1292 ///////////////////////////////////////////////////////////////////