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);
551 if (repokind.toEnum() != RepoType::NONE_e)
553 //save probed type only for repos in system
554 std::list<RepoInfo> repos = knownRepositories();
555 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
556 it != repos.end(); ++it )
558 if ( info.alias() == (*it).alias() )
560 RepoInfo modifiedrepo = info;
561 modifiedrepo.setType(repokind);
562 modifyRepository(info.alias(),modifiedrepo);
571 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
572 filesystem::assert_dir(rawpath);
574 // create temp dir as sibling of rawpath
575 filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( rawpath ) );
577 if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
578 ( repokind.toEnum() == RepoType::YAST2_e ) )
580 MediaSetAccess media(url);
581 shared_ptr<repo::Downloader> downloader_ptr;
583 if ( repokind.toEnum() == RepoType::RPMMD_e )
584 downloader_ptr.reset(new yum::Downloader(info.path()));
586 downloader_ptr.reset( new susetags::Downloader(info.path()));
589 * Given a downloader, sets the other repos raw metadata
590 * path as cache paths for the fetcher, so if another
591 * repo has the same file, it will not download it
592 * but copy it from the other repository
594 std::list<RepoInfo> repos = knownRepositories();
595 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
599 Pathname cachepath(rawcache_path_for_repoinfo( _pimpl->options, *it ));
600 if ( PathInfo(cachepath).isExist() )
601 downloader_ptr->addCachePath(cachepath);
604 downloader_ptr->download( media, tmpdir.path());
607 else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
609 RepoStatus newstatus = parser::plaindir::dirStatus(url.getPathName());
611 std::ofstream file(( tmpdir.path() + "/cookie").c_str());
613 ZYPP_THROW (Exception( "Can't open " + tmpdir.path().asString() + "/cookie" ) );
616 file << newstatus.checksum() << endl;
623 ZYPP_THROW(RepoUnknownTypeException());
626 // ok we have the metadata, now exchange
629 TmpDir oldmetadata( TmpDir::makeSibling( rawpath ) );
630 filesystem::rename( rawpath, oldmetadata.path() );
631 // move the just downloaded there
632 filesystem::rename( tmpdir.path(), rawpath );
637 catch ( const Exception &e )
640 ERR << "Trying another url..." << endl;
642 // remember the exception caught for the *first URL*
643 // if all other URLs fail, the rexception will be thrown with the
644 // cause of the problem of the first URL remembered
645 if (it == info.baseUrlsBegin())
646 rexception.remember(e);
649 ERR << "No more urls..." << endl;
650 ZYPP_THROW(rexception);
653 ////////////////////////////////////////////////////////////////////////////
655 void RepoManager::cleanMetadata( const RepoInfo &info,
656 const ProgressData::ReceiverFnc & progressfnc )
658 ProgressData progress(100);
659 progress.sendTo(progressfnc);
661 filesystem::recursive_rmdir(rawcache_path_for_repoinfo(_pimpl->options, info));
665 void RepoManager::cleanPackages( const RepoInfo &info,
666 const ProgressData::ReceiverFnc & progressfnc )
668 ProgressData progress(100);
669 progress.sendTo(progressfnc);
671 filesystem::recursive_rmdir(packagescache_path_for_repoinfo(_pimpl->options, info));
675 void RepoManager::buildCache( const RepoInfo &info,
676 CacheBuildPolicy policy,
677 const ProgressData::ReceiverFnc & progressrcv )
680 Pathname rawpath = rawcache_path_for_repoinfo(_pimpl->options, info);
682 Pathname base = _pimpl->options.repoCachePath + info.escaped_alias();
683 Pathname solvfile = base.extend(".solv");
686 RepoStatus raw_metadata_status = metadataStatus(info);
687 if ( raw_metadata_status.empty() )
689 /* if there is no cache at this point, we refresh the raw
690 in case this is the first time - if it's !autorefresh,
691 we may still refresh */
692 refreshMetadata(info, RefreshIfNeeded, progressrcv );
693 raw_metadata_status = metadataStatus(info);
696 bool needs_cleaning = false;
697 if ( isCached( info ) )
699 MIL << info.alias() << " is already cached." << endl;
700 //data::RecordId id = store.lookupRepository(info.alias());
701 RepoStatus cache_status = cacheStatus(info);
703 if ( cache_status.checksum() == raw_metadata_status.checksum() )
705 MIL << info.alias() << " cache is up to date with metadata." << endl;
706 if ( policy == BuildIfNeeded ) {
710 MIL << info.alias() << " cache rebuild is forced" << endl;
714 needs_cleaning = true;
717 ProgressData progress(100);
718 callback::SendReport<ProgressReport> report;
719 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
720 progress.name(str::form(_("Building repository '%s' cache"), info.name().c_str()));
728 MIL << info.alias() << " building cache..." << endl;
730 repo::RepoType repokind = info.type();
732 // if the type is unknown, try probing.
733 switch ( repokind.toEnum() )
735 case RepoType::NONE_e:
736 // unknown, probe the local metadata
737 repokind = probe(rawpath.asUrl());
743 MIL << "repo type is " << repokind << endl;
745 switch ( repokind.toEnum() )
747 case RepoType::RPMMD_e :
748 case RepoType::YAST2_e :
750 // Take care we unlink the solvfile on exception
751 ManagedFile guard( solvfile, filesystem::unlink );
754 cmd << str::form( "repo2solv.sh \"%s\" > \"%s\"", rawpath.c_str(), solvfile.c_str() );
756 MIL << "Executing: " << cmd.str() << endl;
757 ExternalProgram prog( cmd.str(), ExternalProgram::Stderr_To_Stdout );
760 for ( string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() ) {
761 WAR << " " << output;
762 cmd << " " << output;
765 int ret = prog.close();
768 RepoException ex(str::form("Failed to cache repo (%d).", ret));
769 ex.remember( cmd.str() );
774 guard.resetDispose();
778 ZYPP_THROW(RepoUnknownTypeException("Unhandled repository type"));
782 switch ( repokind.toEnum() )
784 case RepoType::RPMMD_e :
787 CombinedProgressData subprogrcv( progress, 100);
788 parser::yum::RepoParser parser(id, store, parser::yum::RepoParserOpts(), subprogrcv);
789 parser.parse(rawpath);
793 case RepoType::YAST2_e :
796 CombinedProgressData subprogrcv( progress, 100);
797 parser::susetags::RepoParser parser(id, store, subprogrcv);
798 parser.parse(rawpath);
804 case RepoType::RPMPLAINDIR_e :
806 CombinedProgressData subprogrcv( progress, 100);
807 InputStream is(rawpath + "cookie");
809 getline( is.stream(), buffer);
811 parser::plaindir::RepoParser parser(id, store, subprogrcv);
812 parser.parse(url.getPathName());
817 ZYPP_THROW(RepoUnknownTypeException());
820 // update timestamp and checksum
821 //store.updateRepositoryStatus(id, raw_metadata_status);
822 setCacheStatus(info.escaped_alias(), raw_metadata_status);
823 MIL << "Commit cache.." << endl;
828 ////////////////////////////////////////////////////////////////////////////
830 repo::RepoType RepoManager::probe( const Url &url ) const
832 if ( url.getScheme() == "dir" && ! PathInfo( url.getPathName() ).isDir() )
834 // Handle non existing local directory in advance, as
835 // MediaSetAccess does not support it.
836 return repo::RepoType::NONE;
841 MediaSetAccess access(url);
842 if ( access.doesFileExist("/repodata/repomd.xml") )
843 return repo::RepoType::RPMMD;
844 if ( access.doesFileExist("/content") )
845 return repo::RepoType::YAST2;
847 // if it is a local url of type dir
848 if ( (! media::MediaManager::downloads(url)) && ( url.getScheme() == "dir" ) )
850 Pathname path = Pathname(url.getPathName());
851 if ( PathInfo(path).isDir() )
853 // allow empty dirs for now
854 return repo::RepoType::RPMPLAINDIR;
858 catch ( const media::MediaException &e )
861 RepoException enew("Error trying to read from " + url.asString());
865 catch ( const Exception &e )
868 Exception enew("Unknown error reading from " + url.asString());
873 return repo::RepoType::NONE;
876 ////////////////////////////////////////////////////////////////////////////
878 void RepoManager::cleanCache( const RepoInfo &info,
879 const ProgressData::ReceiverFnc & progressrcv )
881 ProgressData progress(100);
882 progress.sendTo(progressrcv);
885 unlink (_pimpl->options.repoCachePath / (info.escaped_alias() + ".solv"));
887 unlink (_pimpl->options.repoCachePath / (info.escaped_alias() + ".cookie"));
892 void RepoManager::cleanTargetCache(const ProgressData::ReceiverFnc & progressrcv)
894 unlink (_pimpl->options.repoCachePath / (sat::Pool::systemRepoName() + ".solv"));
895 unlink (_pimpl->options.repoCachePath / (sat::Pool::systemRepoName() + ".cookie"));
898 ////////////////////////////////////////////////////////////////////////////
900 bool RepoManager::isCached( const RepoInfo &info ) const
902 Pathname name = _pimpl->options.repoCachePath;
903 return PathInfo(name + Pathname(info.escaped_alias()).extend(".solv")).isExist();
906 RepoStatus RepoManager::cacheStatus( const RepoInfo &info ) const
909 Pathname base = _pimpl->options.repoCachePath + info.escaped_alias();
910 Pathname cookiefile = base.extend(".cookie");
912 return RepoStatus::fromCookieFile(cookiefile);
915 void RepoManager::setCacheStatus( const string &alias, const RepoStatus &status )
917 Pathname base = _pimpl->options.repoCachePath + alias;
918 Pathname cookiefile = base.extend(".cookie");
920 status.saveToCookieFile(cookiefile);
923 void RepoManager::loadFromCache( const RepoInfo & info,
924 const ProgressData::ReceiverFnc & progressrcv )
927 string alias = info.escaped_alias();
928 Pathname solvfile = (_pimpl->options.repoCachePath / alias).extend(".solv");
930 if ( ! PathInfo(solvfile).isExist() )
931 ZYPP_THROW(RepoNotCachedException());
935 sat::Pool::instance().addRepoSolv( solvfile, info );
937 catch ( const Exception & exp )
940 MIL << "Try to handle exception by rebuilding the solv-file" << endl;
941 cleanCache( info, progressrcv );
942 buildCache( info, BuildIfNeeded, progressrcv );
944 sat::Pool::instance().addRepoSolv( solvfile, info );
948 ////////////////////////////////////////////////////////////////////////////
951 * Generate a non existing filename in a directory, using a base
952 * name. For example if a directory contains 3 files
958 * If you try to generate a unique filename for this directory,
959 * based on "ruu" you will get "ruu", but if you use the base
960 * "foo" you will get "foo_1"
962 * \param dir Directory where the file needs to be unique
963 * \param basefilename string to base the filename on.
965 static Pathname generate_non_existing_name( const Pathname &dir,
966 const std::string &basefilename )
968 string final_filename = basefilename;
970 while ( PathInfo(dir + final_filename).isExist() )
972 final_filename = basefilename + "_" + str::numstring(counter);
975 return dir + Pathname(final_filename);
978 ////////////////////////////////////////////////////////////////////////////
981 * \short Generate a related filename from a repo info
983 * From a repo info, it will try to use the alias as a filename
984 * escaping it if necessary. Other fallbacks can be added to
985 * this function in case there is no way to use the alias
987 static std::string generate_filename( const RepoInfo &info )
991 std::string filename = info.alias();
992 // replace slashes with underscores
993 size_t pos = filename.find(fnd);
994 while(pos!=string::npos)
996 filename.replace(pos,fnd.length(),rep);
997 pos = filename.find(fnd,pos+rep.length());
999 filename = Pathname(filename).extend(".repo").asString();
1000 MIL << "generating filename for repo [" << info.alias() << "] : '" << filename << "'" << endl;
1005 ////////////////////////////////////////////////////////////////////////////
1007 void RepoManager::addRepository( const RepoInfo &info,
1008 const ProgressData::ReceiverFnc & progressrcv )
1012 ProgressData progress(100);
1013 callback::SendReport<ProgressReport> report;
1014 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1015 progress.name(str::form(_("Adding repository '%s'"), info.name().c_str()));
1018 std::list<RepoInfo> repos = knownRepositories();
1019 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1023 if ( info.alias() == (*it).alias() )
1024 ZYPP_THROW(RepoAlreadyExistsException(info.alias()));
1027 RepoInfo tosave = info;
1029 // check the first url for now
1030 if ( _pimpl->options.probe )
1032 DBG << "unknown repository type, probing" << endl;
1034 RepoType probedtype;
1035 probedtype = probe(*tosave.baseUrlsBegin());
1036 if ( tosave.baseUrlsSize() > 0 )
1038 if ( probedtype == RepoType::NONE )
1039 ZYPP_THROW(RepoUnknownTypeException());
1041 tosave.setType(probedtype);
1047 // assert the directory exists
1048 filesystem::assert_dir(_pimpl->options.knownReposPath);
1050 Pathname repofile = generate_non_existing_name(_pimpl->options.knownReposPath,
1051 generate_filename(tosave));
1052 // now we have a filename that does not exists
1053 MIL << "Saving repo in " << repofile << endl;
1055 std::ofstream file(repofile.c_str());
1057 ZYPP_THROW (Exception( "Can't open " + repofile.asString() ) );
1060 tosave.dumpRepoOn(file);
1062 MIL << "done" << endl;
1065 void RepoManager::addRepositories( const Url &url,
1066 const ProgressData::ReceiverFnc & progressrcv )
1068 std::list<RepoInfo> knownrepos = knownRepositories();
1069 std::list<RepoInfo> repos = readRepoFile(url);
1070 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1074 // look if the alias is in the known repos.
1075 for ( std::list<RepoInfo>::const_iterator kit = knownrepos.begin();
1076 kit != knownrepos.end();
1079 if ( (*it).alias() == (*kit).alias() )
1081 ERR << "To be added repo " << (*it).alias() << " conflicts with existing repo " << (*kit).alias() << endl;
1082 ZYPP_THROW(RepoAlreadyExistsException((*it).alias()));
1087 string filename = Pathname(url.getPathName()).basename();
1089 if ( filename == Pathname() )
1090 ZYPP_THROW(RepoException("Invalid repo file name at " + url.asString() ));
1092 // assert the directory exists
1093 filesystem::assert_dir(_pimpl->options.knownReposPath);
1095 Pathname repofile = generate_non_existing_name(_pimpl->options.knownReposPath, filename);
1096 // now we have a filename that does not exists
1097 MIL << "Saving " << repos.size() << " repo" << ( repos.size() ? "s" : "" ) << " in " << repofile << endl;
1099 std::ofstream file(repofile.c_str());
1101 ZYPP_THROW (Exception( "Can't open " + repofile.asString() ) );
1104 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1108 MIL << "Saving " << (*it).alias() << endl;
1109 (*it).dumpRepoOn(file);
1111 MIL << "done" << endl;
1114 ////////////////////////////////////////////////////////////////////////////
1116 void RepoManager::removeRepository( const RepoInfo & info,
1117 const ProgressData::ReceiverFnc & progressrcv)
1119 ProgressData progress;
1120 callback::SendReport<ProgressReport> report;
1121 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1122 progress.name(str::form(_("Removing repository '%s'"), info.name().c_str()));
1124 MIL << "Going to delete repo " << info.alias() << endl;
1126 std::list<RepoInfo> repos = knownRepositories();
1127 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1131 // they can be the same only if the provided is empty, that means
1132 // the provided repo has no alias
1134 if ( (!info.alias().empty()) && ( info.alias() != (*it).alias() ) )
1137 // TODO match by url
1139 // we have a matcing repository, now we need to know
1140 // where it does come from.
1141 RepoInfo todelete = *it;
1142 if (todelete.filepath().empty())
1144 ZYPP_THROW(RepoException("Can't figure where the repo is stored"));
1148 // figure how many repos are there in the file:
1149 std::list<RepoInfo> filerepos = repositories_in_file(todelete.filepath());
1150 if ( (filerepos.size() == 1) && ( filerepos.front().alias() == todelete.alias() ) )
1152 // easy, only this one, just delete the file
1153 if ( filesystem::unlink(todelete.filepath()) != 0 )
1155 ZYPP_THROW(RepoException("Can't delete " + todelete.filepath().asString()));
1157 MIL << todelete.alias() << " sucessfully deleted." << endl;
1161 // there are more repos in the same file
1162 // write them back except the deleted one.
1164 //std::ofstream file(tmp.path().c_str());
1166 // assert the directory exists
1167 filesystem::assert_dir(todelete.filepath().dirname());
1169 std::ofstream file(todelete.filepath().c_str());
1171 //ZYPP_THROW (Exception( "Can't open " + tmp.path().asString() ) );
1172 ZYPP_THROW (Exception( "Can't open " + todelete.filepath().asString() ) );
1174 for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1175 fit != filerepos.end();
1178 if ( (*fit).alias() != todelete.alias() )
1179 (*fit).dumpRepoOn(file);
1183 CombinedProgressData subprogrcv(progress, 70);
1184 CombinedProgressData cleansubprogrcv(progress, 30);
1185 // now delete it from cache
1186 if ( isCached(todelete) )
1187 cleanCache( todelete, subprogrcv);
1188 // now delete metadata (#301037)
1189 cleanMetadata( todelete, cleansubprogrcv);
1190 MIL << todelete.alias() << " sucessfully deleted." << endl;
1192 } // else filepath is empty
1195 // should not be reached on a sucess workflow
1196 ZYPP_THROW(RepoNotFoundException(info));
1199 ////////////////////////////////////////////////////////////////////////////
1201 void RepoManager::modifyRepository( const std::string &alias,
1202 const RepoInfo & newinfo,
1203 const ProgressData::ReceiverFnc & progressrcv )
1205 RepoInfo toedit = getRepositoryInfo(alias);
1207 // check if the new alias already exists when renaming the repo
1208 if (alias != newinfo.alias())
1210 std::list<RepoInfo> repos = knownRepositories();
1211 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1215 if ( newinfo.alias() == (*it).alias() )
1216 ZYPP_THROW(RepoAlreadyExistsException(newinfo.alias()));
1220 if (toedit.filepath().empty())
1222 ZYPP_THROW(RepoException("Can't figure where the repo is stored"));
1226 // figure how many repos are there in the file:
1227 std::list<RepoInfo> filerepos = repositories_in_file(toedit.filepath());
1229 // there are more repos in the same file
1230 // write them back except the deleted one.
1232 //std::ofstream file(tmp.path().c_str());
1234 // assert the directory exists
1235 filesystem::assert_dir(toedit.filepath().dirname());
1237 std::ofstream file(toedit.filepath().c_str());
1239 //ZYPP_THROW (Exception( "Can't open " + tmp.path().asString() ) );
1240 ZYPP_THROW (Exception( "Can't open " + toedit.filepath().asString() ) );
1242 for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1243 fit != filerepos.end();
1246 // if the alias is different, dump the original
1247 // if it is the same, dump the provided one
1248 if ( (*fit).alias() != toedit.alias() )
1249 (*fit).dumpRepoOn(file);
1251 newinfo.dumpRepoOn(file);
1256 ////////////////////////////////////////////////////////////////////////////
1258 RepoInfo RepoManager::getRepositoryInfo( const std::string &alias,
1259 const ProgressData::ReceiverFnc & progressrcv )
1261 std::list<RepoInfo> repos = knownRepositories();
1262 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1266 if ( (*it).alias() == alias )
1270 info.setAlias(info.alias());
1271 ZYPP_THROW(RepoNotFoundException(info));
1274 ////////////////////////////////////////////////////////////////////////////
1276 RepoInfo RepoManager::getRepositoryInfo( const Url & url,
1277 const url::ViewOption & urlview,
1278 const ProgressData::ReceiverFnc & progressrcv )
1280 std::list<RepoInfo> repos = knownRepositories();
1281 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1285 for(RepoInfo::urls_const_iterator urlit = (*it).baseUrlsBegin();
1286 urlit != (*it).baseUrlsEnd();
1289 if ((*urlit).asString(urlview) == url.asString(urlview))
1294 info.setAlias(info.alias());
1295 info.setBaseUrl(url);
1296 ZYPP_THROW(RepoNotFoundException(info));
1299 ////////////////////////////////////////////////////////////////////////////
1301 std::ostream & operator<<( std::ostream & str, const RepoManager & obj )
1303 return str << *obj._pimpl;
1306 /////////////////////////////////////////////////////////////////
1308 ///////////////////////////////////////////////////////////////////