YaST Commits
Threads by month
- ----- 2025 -----
- February
- January
- ----- 2024 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2023 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2022 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2021 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2020 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2019 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2018 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2017 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2016 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2015 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2014 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2013 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2012 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2011 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2010 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2009 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2008 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2007 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
December 2007
- 21 participants
- 683 discussions

[yast-commit] r42759 - in /trunk/gtk/unstable-libyui: ChangeLog src/YGUI.cc
by rpmcruz@svn.opensuse.org 06 Dec '07
by rpmcruz@svn.opensuse.org 06 Dec '07
06 Dec '07
Author: rpmcruz
Date: Thu Dec 6 14:13:10 2007
New Revision: 42759
URL: http://svn.opensuse.org/viewcvs/yast?rev=42759&view=rev
Log:
Removed bug line on changelog -- it was caused by somehting else...
Some printfs to ygui.
Modified:
trunk/gtk/unstable-libyui/ChangeLog
trunk/gtk/unstable-libyui/src/YGUI.cc
Modified: trunk/gtk/unstable-libyui/ChangeLog
URL: http://svn.opensuse.org/viewcvs/yast/trunk/gtk/unstable-libyui/ChangeLog?re…
==============================================================================
--- trunk/gtk/unstable-libyui/ChangeLog (original)
+++ trunk/gtk/unstable-libyui/ChangeLog Thu Dec 6 14:13:10 2007
@@ -2,7 +2,6 @@
* Fixed previous crash, some other problems and some improvements.
* Weird problems left:
- + it hangs when suposedly the code is already terminated.
+ crashes on sw_single (says we are calling a pure virtual func)
sometimes, it just exists normally right after the selector widget
appears
Modified: trunk/gtk/unstable-libyui/src/YGUI.cc
URL: http://svn.opensuse.org/viewcvs/yast/trunk/gtk/unstable-libyui/src/YGUI.cc?…
==============================================================================
--- trunk/gtk/unstable-libyui/src/YGUI.cc (original)
+++ trunk/gtk/unstable-libyui/src/YGUI.cc Thu Dec 6 14:13:10 2007
@@ -109,10 +109,14 @@
}
}
+#define PRINT_EVENTS
+
void YGUI::idleLoop (int fd_ycp)
{
IMPL
-//fprintf (stderr, "idleLoop()\n");
+#ifdef PRINT_EVENTS
+fprintf (stderr, "idleLoop()\n");
+#endif
// The rational for this is that we need somewhere to run
// the magic 'main' thread, that can process thread unsafe
// incoming CORBA messages for us
@@ -131,7 +135,9 @@
g_source_remove (watch_tag);
g_io_channel_unref (wakeup);
-//fprintf (stderr, "no more idle\n");
+#ifdef PRINT_EVENTS
+fprintf (stderr, "no more idle\n");
+#endif
}
static gboolean user_input_timeout_cb (YGUI *pThis)
@@ -152,7 +158,9 @@
YEvent *YGUI::waitInput (unsigned long timeout_ms, bool block)
{
IMPL
-//fprintf (stderr, "waitInput()\n");
+#ifdef PRINT_EVENTS
+fprintf (stderr, "waitInput()\n");
+#endif
if (!YDialog::currentDialog (false))
return NULL;
@@ -183,7 +191,9 @@
if (block) // if YCP keeps working for more than X time, set busy cursor
busy_timeout = g_timeout_add (BUSY_CURSOR_TIMEOUT, busy_timeout_cb, this);
-//fprintf (stderr, "returning event: %s\n", !event ? "(none)" : YEvent::toString (event->eventType()));
+#ifdef PRINT_EVENTS
+fprintf (stderr, "returning event: %s\n", !event ? "(none)" : YEvent::toString (event->eventType()));
+#endif
return event;
}
--
To unsubscribe, e-mail: yast-commit+unsubscribe(a)opensuse.org
For additional commands, e-mail: yast-commit+help(a)opensuse.org
1
0

[yast-commit] r42758 - in /branches/tmp/coolo/qt4-port/src: YQMainWinDock.cc YQMultiSelectionBox.cc YQSelectionBox.cc YQTable.cc YQTree.cc YQWizard.cc
by dmacvicar@svn.opensuse.org 06 Dec '07
by dmacvicar@svn.opensuse.org 06 Dec '07
06 Dec '07
Author: dmacvicar
Date: Thu Dec 6 13:44:57 2007
New Revision: 42758
URL: http://svn.opensuse.org/viewcvs/yast?rev=42758&view=rev
Log:
make it work for now
Modified:
branches/tmp/coolo/qt4-port/src/YQMainWinDock.cc
branches/tmp/coolo/qt4-port/src/YQMultiSelectionBox.cc
branches/tmp/coolo/qt4-port/src/YQSelectionBox.cc
branches/tmp/coolo/qt4-port/src/YQTable.cc
branches/tmp/coolo/qt4-port/src/YQTree.cc
branches/tmp/coolo/qt4-port/src/YQWizard.cc
Modified: branches/tmp/coolo/qt4-port/src/YQMainWinDock.cc
URL: http://svn.opensuse.org/viewcvs/yast/branches/tmp/coolo/qt4-port/src/YQMain…
==============================================================================
--- branches/tmp/coolo/qt4-port/src/YQMainWinDock.cc (original)
+++ branches/tmp/coolo/qt4-port/src/YQMainWinDock.cc Thu Dec 6 13:44:57 2007
@@ -224,6 +224,9 @@
bool
YQMainWinDock::couldDock()
{
+ //FIXME
+ return false;
+
YDialog * topDialog = YDialog::topmostDialog( false ); // don't throw
if ( ! topDialog ) // No dialog at all?
Modified: branches/tmp/coolo/qt4-port/src/YQMultiSelectionBox.cc
URL: http://svn.opensuse.org/viewcvs/yast/branches/tmp/coolo/qt4-port/src/YQMult…
==============================================================================
--- branches/tmp/coolo/qt4-port/src/YQMultiSelectionBox.cc (original)
+++ branches/tmp/coolo/qt4-port/src/YQMultiSelectionBox.cc Thu Dec 6 13:44:57 2007
@@ -68,7 +68,7 @@
// Very small default size if specified
- connect( _qt_listView, SIGNAL( selectionChanged() ),
+ connect( _qt_listView, SIGNAL( itemSelectionChanged() ),
this, SLOT ( slotSelected() ) );
connect( this, SIGNAL( valueChanged() ),
Modified: branches/tmp/coolo/qt4-port/src/YQSelectionBox.cc
URL: http://svn.opensuse.org/viewcvs/yast/branches/tmp/coolo/qt4-port/src/YQSele…
==============================================================================
--- branches/tmp/coolo/qt4-port/src/YQSelectionBox.cc (original)
+++ branches/tmp/coolo/qt4-port/src/YQSelectionBox.cc Thu Dec 6 13:44:57 2007
@@ -73,7 +73,7 @@
connect( _qt_listBox, SIGNAL( highlighted ( int ) ),
this, SLOT ( slotSelected( int ) ) );
- connect( _qt_listBox, SIGNAL( doubleClicked( QListWidgetItem * ) ),
+ connect( _qt_listBox, SIGNAL( itemDoubleClicked( QListWidgetItem * ) ),
this, SLOT ( slotActivated( QListWidgetItem * ) ) );
connect( &_timer, SIGNAL( timeout() ),
Modified: branches/tmp/coolo/qt4-port/src/YQTable.cc
URL: http://svn.opensuse.org/viewcvs/yast/branches/tmp/coolo/qt4-port/src/YQTabl…
==============================================================================
--- branches/tmp/coolo/qt4-port/src/YQTable.cc (original)
+++ branches/tmp/coolo/qt4-port/src/YQTable.cc Thu Dec 6 13:44:57 2007
@@ -79,13 +79,13 @@
// Connect signals and slots
//
- connect( _qt_listView, SIGNAL( doubleClicked ( QTreeWidgetItem * ) ),
+ connect( _qt_listView, SIGNAL( itemDoubleClicked ( QTreeWidgetItem *, int ) ),
this, SLOT ( slotActivated ( QTreeWidgetItem * ) ) );
connect( _qt_listView, SIGNAL( spacePressed ( QTreeWidgetItem * ) ),
this, SLOT ( slotActivated ( QTreeWidgetItem * ) ) );
- connect( _qt_listView, SIGNAL( selectionChanged ( QTreeWidgetItem * ) ),
+ connect( _qt_listView, SIGNAL( currentItemChanged ( QTreeWidgetItem *, QTreeWidgetItem * ) ),
this, SLOT ( slotSelected ( QTreeWidgetItem * ) ) );
}
Modified: branches/tmp/coolo/qt4-port/src/YQTree.cc
URL: http://svn.opensuse.org/viewcvs/yast/branches/tmp/coolo/qt4-port/src/YQTree…
==============================================================================
--- branches/tmp/coolo/qt4-port/src/YQTree.cc (original)
+++ branches/tmp/coolo/qt4-port/src/YQTree.cc Thu Dec 6 13:44:57 2007
@@ -71,13 +71,13 @@
_caption->setBuddy ( _qt_listView );
- connect( _qt_listView, SIGNAL( selectionChanged ( QTreeWidgetItem * ) ),
+ connect( _qt_listView, SIGNAL( itemSelectionChanged ( QTreeWidgetItem *, QTreeWidgetItem * ) ),
this, SLOT ( slotSelected ( QTreeWidgetItem * ) ) );
connect( _qt_listView, SIGNAL( spacePressed ( QTreeWidgetItem * ) ),
this, SLOT ( slotActivated ( QTreeWidgetItem * ) ) );
- connect( _qt_listView, SIGNAL( doubleClicked ( QTreeWidgetItem * ) ),
+ connect( _qt_listView, SIGNAL( itemDoubleClicked ( QTreeWidgetItem *, int) ),
this, SLOT ( slotActivated ( QTreeWidgetItem * ) ) );
}
Modified: branches/tmp/coolo/qt4-port/src/YQWizard.cc
URL: http://svn.opensuse.org/viewcvs/yast/branches/tmp/coolo/qt4-port/src/YQWiza…
==============================================================================
--- branches/tmp/coolo/qt4-port/src/YQWizard.cc (original)
+++ branches/tmp/coolo/qt4-port/src/YQWizard.cc Thu Dec 6 13:44:57 2007
@@ -500,13 +500,13 @@
_tree->setRootIsDecorated( true );
_tree->setSortByInsertionSequence( true );
- connect( _tree, SIGNAL( selectionChanged ( void ) ),
+ connect( _tree, SIGNAL( itemSelectionChanged ( void ) ),
this, SLOT ( treeSelectionChanged ( void ) ) );
connect( _tree, SIGNAL( spacePressed ( QTreeWidgetItem * ) ),
this, SLOT ( sendTreeEvent ( QTreeWidgetItem * ) ) );
- connect( _tree, SIGNAL( doubleClicked ( QTreeWidgetItem * ) ),
+ connect( _tree, SIGNAL( itemDoubleClicked ( QTreeWidgetItem *, int ) ),
this, SLOT ( sendTreeEvent ( QTreeWidgetItem * ) ) );
}
--
To unsubscribe, e-mail: yast-commit+unsubscribe(a)opensuse.org
For additional commands, e-mail: yast-commit+help(a)opensuse.org
1
0

[yast-commit] r42757 - in /trunk/gtk/unstable-libyui/src: YGTime.cc YGTree.cc
by rpmcruz@svn.opensuse.org 06 Dec '07
by rpmcruz@svn.opensuse.org 06 Dec '07
06 Dec '07
Author: rpmcruz
Date: Thu Dec 6 13:43:27 2007
New Revision: 42757
URL: http://svn.opensuse.org/viewcvs/yast?rev=42757&view=rev
Log:
Files no longer needed.
YGTree is now on YGTable
YGTime gone to YGInputField
Removed:
trunk/gtk/unstable-libyui/src/YGTime.cc
trunk/gtk/unstable-libyui/src/YGTree.cc
--
To unsubscribe, e-mail: yast-commit+unsubscribe(a)opensuse.org
For additional commands, e-mail: yast-commit+help(a)opensuse.org
1
0

[yast-commit] r42756 - in /trunk/gtk/unstable-libyui: ./ src/
by rpmcruz@svn.opensuse.org 06 Dec '07
by rpmcruz@svn.opensuse.org 06 Dec '07
06 Dec '07
Author: rpmcruz
Date: Thu Dec 6 13:42:24 2007
New Revision: 42756
URL: http://svn.opensuse.org/viewcvs/yast?rev=42756&view=rev
Log:
* Fixed previous crash, some other problems and some improvements.
* Weird problems left:
+ it hangs when suposedly the code is already terminated.
+ crashes on sw_single (says we are calling a pure virtual func)
sometimes, it just exists normally right after the selector widget
appears
+ there could be layout probs... test that
+ radio buttons are not working
Modified:
trunk/gtk/unstable-libyui/ChangeLog
trunk/gtk/unstable-libyui/src/Makefile.am
trunk/gtk/unstable-libyui/src/YGBarGraph.cc
trunk/gtk/unstable-libyui/src/YGComboBox.cc
trunk/gtk/unstable-libyui/src/YGDialog.cc
trunk/gtk/unstable-libyui/src/YGDumbTab.cc
trunk/gtk/unstable-libyui/src/YGFrame.cc
trunk/gtk/unstable-libyui/src/YGImage.cc
trunk/gtk/unstable-libyui/src/YGInputField.cc
trunk/gtk/unstable-libyui/src/YGIntField.cc
trunk/gtk/unstable-libyui/src/YGLabel.cc
trunk/gtk/unstable-libyui/src/YGLayout.cc
trunk/gtk/unstable-libyui/src/YGMenuButton.cc
trunk/gtk/unstable-libyui/src/YGMultiLineEdit.cc
trunk/gtk/unstable-libyui/src/YGPackageSelector.cc
trunk/gtk/unstable-libyui/src/YGProgressBar.cc
trunk/gtk/unstable-libyui/src/YGPushButton.cc
trunk/gtk/unstable-libyui/src/YGRadioButton.cc
trunk/gtk/unstable-libyui/src/YGSelectionModel.cc
trunk/gtk/unstable-libyui/src/YGSelectionModel.h
trunk/gtk/unstable-libyui/src/YGTable.cc
trunk/gtk/unstable-libyui/src/YGUI.cc
trunk/gtk/unstable-libyui/src/YGUI.h
trunk/gtk/unstable-libyui/src/YGWidget.cc
trunk/gtk/unstable-libyui/src/YGWidget.h
trunk/gtk/unstable-libyui/src/YGWizard.cc
trunk/gtk/unstable-libyui/src/ygtkfieldentry.c
trunk/gtk/unstable-libyui/src/ygtkfieldentry.h
trunk/gtk/unstable-libyui/src/ygtkrichtext.c
trunk/gtk/unstable-libyui/src/ygtkwizard.c
trunk/gtk/unstable-libyui/src/ygtkwizard.h
Modified: trunk/gtk/unstable-libyui/ChangeLog
URL: http://svn.opensuse.org/viewcvs/yast/trunk/gtk/unstable-libyui/ChangeLog?re…
==============================================================================
--- trunk/gtk/unstable-libyui/ChangeLog (original)
+++ trunk/gtk/unstable-libyui/ChangeLog Thu Dec 6 13:42:24 2007
@@ -1,3 +1,20 @@
+2007-12-06 Ricardo Cruz <rpmcruz(a)alunos.dcc.fc.up.pt>
+
+ * Fixed previous crash, some other problems and some improvements.
+ * Weird problems left:
+ + it hangs when suposedly the code is already terminated.
+ + crashes on sw_single (says we are calling a pure virtual func)
+ sometimes, it just exists normally right after the selector widget
+ appears
+ + there could be layout probs... test that
+ + radio buttons are not working
+
+2007-12-05 Ricardo Cruz <rpmcruz(a)alunos.dcc.fc.up.pt>
+
+ * First version: ported the all thing; getting a crash due to child
+ being added to container at the YWidget() constructor, before we get to
+ setup the reference to then use on the layout widget.
+
2007-12-04 Ricardo Cruz <rpmcruz(a)alunos.dcc.fc.up.pt>
* src/ygtkimage.h/c: moved YGImage stuff to an actual widget impl. Added
Modified: trunk/gtk/unstable-libyui/src/Makefile.am
URL: http://svn.opensuse.org/viewcvs/yast/trunk/gtk/unstable-libyui/src/Makefile…
==============================================================================
--- trunk/gtk/unstable-libyui/src/Makefile.am (original)
+++ trunk/gtk/unstable-libyui/src/Makefile.am Thu Dec 6 13:42:24 2007
@@ -38,7 +38,6 @@
YGBarGraph.cc \
YGDumbTab.cc \
YGWizard.cc \
- YGTime.cc \
YGPackageSelector.cc \
ygtkratiobox.c \
ygtkbargraph.c \
Modified: trunk/gtk/unstable-libyui/src/YGBarGraph.cc
URL: http://svn.opensuse.org/viewcvs/yast/trunk/gtk/unstable-libyui/src/YGBarGra…
==============================================================================
--- trunk/gtk/unstable-libyui/src/YGBarGraph.cc (original)
+++ trunk/gtk/unstable-libyui/src/YGBarGraph.cc Thu Dec 6 13:42:24 2007
@@ -14,7 +14,7 @@
{
public:
YGBarGraph (YWidget *parent)
- : YBarGraph (parent)
+ : YBarGraph (NULL)
, YGWidget (this, parent, true, YGTK_TYPE_BAR_GRAPH, NULL)
{}
@@ -27,7 +27,7 @@
ygtk_bar_graph_setup_entry (YGTK_BAR_GRAPH (getWidget()), i,
s.label().c_str(), s.value());
}
- // FIXME: new libyui colors segments ... We probably should honor it
+ // FIXME: new libyui colors segments ... We probably should honor that
}
YGWIDGET_IMPL_COMMON
@@ -49,7 +49,7 @@
YGPartitionSplitter (YWidget *parent, int usedSize, int totalFreeSize, int newPartSize,
int minNewPartSize, int minFreeSize, const string &usedLabel, const string &freeLabel,
const string &newPartLabel, const string &freeFieldLabel, const string &newPartFieldLabel)
- : YPartitionSplitter (parent, usedSize, totalFreeSize, newPartSize, minNewPartSize,
+ : YPartitionSplitter (NULL, usedSize, totalFreeSize, newPartSize, minNewPartSize,
minFreeSize, usedLabel, freeLabel, newPartLabel, freeFieldLabel, newPartFieldLabel)
, YGWidget (this, parent, true, GTK_TYPE_VBOX, NULL)
{
Modified: trunk/gtk/unstable-libyui/src/YGComboBox.cc
URL: http://svn.opensuse.org/viewcvs/yast/trunk/gtk/unstable-libyui/src/YGComboB…
==============================================================================
--- trunk/gtk/unstable-libyui/src/YGComboBox.cc (original)
+++ trunk/gtk/unstable-libyui/src/YGComboBox.cc Thu Dec 6 13:42:24 2007
@@ -14,7 +14,7 @@
{
public:
YGComboBox (YWidget *parent, const string &label, bool editable)
- : YComboBox (parent, label, editable)
+ : YComboBox (NULL, label, editable)
, YGLabeledWidget (this, parent, label, YD_HORIZ, true,
editable ? GTK_TYPE_COMBO_BOX_ENTRY : GTK_TYPE_COMBO_BOX, NULL)
, YGSelectionModel (true, false)
@@ -33,6 +33,7 @@
gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (getWidget()), cell, FALSE);
gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (getWidget()), cell,
"pixbuf", YGSelectionModel::ICON_COLUMN, NULL);
+ gtk_combo_box_set_model (getComboBox(), getModel());
g_signal_connect (G_OBJECT (getWidget()), "changed",
G_CALLBACK (selected_changed_cb), this);
@@ -41,11 +42,6 @@
inline GtkComboBox *getComboBox()
{ return GTK_COMBO_BOX (getWidget()); }
- virtual void setModel (GtkTreeModel *model)
- {
- gtk_combo_box_set_model (getComboBox(), model);
- }
-
GtkEntry *getEntry()
{
if (!GTK_IS_COMBO_BOX_ENTRY (getWidget())) {
Modified: trunk/gtk/unstable-libyui/src/YGDialog.cc
URL: http://svn.opensuse.org/viewcvs/yast/trunk/gtk/unstable-libyui/src/YGDialog…
==============================================================================
--- trunk/gtk/unstable-libyui/src/YGDialog.cc (original)
+++ trunk/gtk/unstable-libyui/src/YGDialog.cc Thu Dec 6 13:42:24 2007
@@ -69,6 +69,9 @@
gtk_window_set_default_size (window, w, h);
}
+ if (YGUI::ui()->setFullscreen())
+ gtk_window_fullscreen (window);
+
gtk_window_set_role (window, "yast-gtk");
if (!YGUI::ui()->hasWM())
g_signal_connect (G_OBJECT (m_widget), "expose-event",
@@ -258,22 +261,12 @@
: YDialog (dialogType, colorMode),
YGWidget (this, NULL, FALSE, GTK_TYPE_HBOX, NULL)
{
-fprintf(stderr, "ygdialog()\n");
setBorder (0);
-fprintf(stderr, "border\n");
m_containee = gtk_event_box_new();
-fprintf(stderr, "containee\n");
if (dialogType == YMainDialog && main_window)
-{
-fprintf(stderr, "use main window\n");
m_window = main_window;
-}
else
-{
-fprintf(stderr, "create window\n");
m_window = new YGWindow (dialogType == YMainDialog);
-}
-fprintf(stderr, "ygdialog start window: %p\n", m_window);
YGWindow::ref (m_window);
if (colorMode != YDialogNormalColor) {
@@ -351,7 +344,7 @@
YGDialog *YGDialog::currentDialog()
{
- YDialog *ydialog = YDialog::currentDialog();
+ YDialog *ydialog = YDialog::currentDialog (false);
if (ydialog)
return static_cast <YGDialog *> (ydialog);
return NULL;
@@ -360,10 +353,8 @@
GtkWindow *YGDialog::currentWindow()
{
YGDialog *ydialog = YGDialog::currentDialog();
- if (ydialog) {
-fprintf(stderr, "m_window: %p\n", ydialog->m_window);
+ if (ydialog)
return GTK_WINDOW (ydialog->m_window->getWidget());
- }
return NULL;
}
@@ -398,7 +389,6 @@
YDialog *YGWidgetFactory::createDialog (YDialogType dialogType, YDialogColorMode colorMode)
{
IMPL
-fprintf(stderr, "create dialog\n");
return new YGDialog (dialogType, colorMode);
}
Modified: trunk/gtk/unstable-libyui/src/YGDumbTab.cc
URL: http://svn.opensuse.org/viewcvs/yast/trunk/gtk/unstable-libyui/src/YGDumbTa…
==============================================================================
--- trunk/gtk/unstable-libyui/src/YGDumbTab.cc (original)
+++ trunk/gtk/unstable-libyui/src/YGDumbTab.cc Thu Dec 6 13:42:24 2007
@@ -18,14 +18,13 @@
public:
YGDumbTab (YWidget *parent)
- : YDumbTab (parent),
+ : YDumbTab (NULL),
YGWidget (this, parent, true, GTK_TYPE_NOTEBOOK, NULL)
{
IMPL
m_containee = gtk_event_box_new();
gtk_widget_show (m_containee);
- g_object_ref (G_OBJECT (m_containee));
- gtk_object_sink (GTK_OBJECT (m_containee));
+ g_object_ref_sink (G_OBJECT (m_containee));
m_last_tab = 0;
// GTK+ keeps the notebook size set to the biggset page. We can't
@@ -33,8 +32,8 @@
// reduce its size.
ygtk_adj_size_set_only_expand (YGTK_ADJ_SIZE (m_adj_size), TRUE);
- g_signal_connect (G_OBJECT (getWidget()), "switch-page",
- G_CALLBACK (changed_tab_cb), this);
+ g_signal_connect_after (G_OBJECT (getWidget()), "switch-page",
+ G_CALLBACK (changed_tab_cb), this);
}
~YGDumbTab()
@@ -49,7 +48,7 @@
GtkWidget *tab_label, *image = 0, *label;
string str = YGUtils::mapKBAccel (item->label());
- label = gtk_label_new (str.c_str());
+ label = gtk_label_new_with_mnemonic (str.c_str());
gtk_widget_show (label);
if (item->hasIconName()) {
@@ -70,15 +69,15 @@
GtkNotebook *notebook = GTK_NOTEBOOK (getWidget());
g_signal_handlers_block_by_func (notebook, (gpointer) changed_tab_cb, this);
- GtkWidget *empty = gtk_event_box_new();
+ GtkWidget *page = gtk_event_box_new();
+ gtk_widget_show (page);
+ item->setData ((void *) page);
+ g_object_set_data (G_OBJECT (page), "yitem", item);
- g_object_set_data (G_OBJECT (empty), "yitem", item);
- gtk_widget_show (empty);
+ gtk_notebook_append_page (notebook, page, tab_label);
- gtk_notebook_append_page (notebook, empty, tab_label);
-
- if (!m_last_tab)
- change_tab (0);
+ if (!m_last_tab) /*first tab*/
+ syncTabPage();
g_signal_handlers_unblock_by_func (notebook, (gpointer) changed_tab_cb, this);
}
@@ -86,16 +85,14 @@
virtual void deleteAllItems()
{
GList *children = gtk_container_get_children (GTK_CONTAINER (getWidget()));
- for (GList *i = children; i; i = i->next) {
- GtkWidget *child = (GtkWidget *) i->data;
- gtk_container_remove (GTK_CONTAINER (getWidget()), child);
- }
+ for (GList *i = children; i; i = i->next)
+ gtk_container_remove (GTK_CONTAINER (getWidget()), (GtkWidget *) i->data);
g_list_free (children);
}
// to re-use the same widget in all tabs (m_fixed), we will remove and
// add to the tabs' child as tabs are changed
- void change_tab (int tab_nb)
+ void syncTabPage()
{
if (m_last_tab)
gtk_container_remove (GTK_CONTAINER (m_last_tab), m_containee);
@@ -121,22 +118,15 @@
{
IMPL
if (selected) {
- GList *children = gtk_container_get_children (GTK_CONTAINER (getWidget()));
- int nb = 0;
- for (GList *i = children; i; i = i->next) {
- GtkWidget *child = (GtkWidget *) i->data;
- if (g_object_get_data (G_OBJECT (child), "yitem") == item) {
- change_tab (nb);
- g_signal_handlers_block_by_func (getWidget(),
- (gpointer) changed_tab_cb, this);
- gtk_notebook_set_current_page (GTK_NOTEBOOK (getWidget()), nb);
- g_signal_handlers_unblock_by_func (getWidget(),
- (gpointer) changed_tab_cb, this);
- break;
- }
- nb++;
- }
- g_list_free (children);
+ GtkWidget *child = (GtkWidget *) item->data();
+ int page = gtk_notebook_page_num (GTK_NOTEBOOK (getWidget()), child);
+
+ g_signal_handlers_block_by_func (getWidget(),
+ (gpointer) changed_tab_cb, this);
+ gtk_notebook_set_current_page (GTK_NOTEBOOK (getWidget()), page);
+ g_signal_handlers_unblock_by_func (getWidget(),
+ (gpointer) changed_tab_cb, this);
+ syncTabPage();
}
}
@@ -147,7 +137,7 @@
YItem *item = (YItem *) g_object_get_data (G_OBJECT (child), "yitem");
YGUI::ui()->sendEvent (new YMenuEvent (item));
- pThis->change_tab (tab_nb);
+ pThis->syncTabPage();
}
YGWIDGET_IMPL_COMMON
Modified: trunk/gtk/unstable-libyui/src/YGFrame.cc
URL: http://svn.opensuse.org/viewcvs/yast/trunk/gtk/unstable-libyui/src/YGFrame.…
==============================================================================
--- trunk/gtk/unstable-libyui/src/YGFrame.cc (original)
+++ trunk/gtk/unstable-libyui/src/YGFrame.cc Thu Dec 6 13:42:24 2007
@@ -37,7 +37,7 @@
{
public:
YGFrame (YWidget *parent, const string &label)
- : YFrame (parent, label),
+ : YFrame (NULL, label),
YGBaseFrame (this, parent)
{
GtkWidget *label_widget = gtk_label_new ("");
@@ -86,7 +86,7 @@
{
public:
YGCheckBoxFrame (YWidget *parent, const string &label, bool checked)
- : YCheckBoxFrame (parent, label, checked),
+ : YCheckBoxFrame (NULL, label, checked),
YGBaseFrame (this, parent)
{
IMPL
Modified: trunk/gtk/unstable-libyui/src/YGImage.cc
URL: http://svn.opensuse.org/viewcvs/yast/trunk/gtk/unstable-libyui/src/YGImage.…
==============================================================================
--- trunk/gtk/unstable-libyui/src/YGImage.cc (original)
+++ trunk/gtk/unstable-libyui/src/YGImage.cc Thu Dec 6 13:42:24 2007
@@ -14,7 +14,7 @@
{
public:
YGImage (YWidget *parent, const string &filename, bool animated)
- : YImage (parent, filename, animated),
+ : YImage (NULL, filename, animated),
YGWidget (this, parent, true, YGTK_TYPE_IMAGE, NULL)
{
IMPL
Modified: trunk/gtk/unstable-libyui/src/YGInputField.cc
URL: http://svn.opensuse.org/viewcvs/yast/trunk/gtk/unstable-libyui/src/YGInputF…
==============================================================================
--- trunk/gtk/unstable-libyui/src/YGInputField.cc (original)
+++ trunk/gtk/unstable-libyui/src/YGInputField.cc Thu Dec 6 13:42:24 2007
@@ -14,44 +14,54 @@
{
public:
YGInputField (YWidget *parent, const string &label, bool passwordMode)
- : YInputField (parent, label, passwordMode),
+ : YInputField (NULL, label, passwordMode),
YGLabeledWidget (this, parent, label, YD_HORIZ, true,
- GTK_TYPE_ENTRY, NULL)
+ YGTK_TYPE_FIELD_ENTRY, NULL)
{
- gtk_entry_set_activates_default (GTK_ENTRY (getWidget()), TRUE);
+ YGtkFieldEntry *field = YGTK_FIELD_ENTRY (getWidget());
+ ygtk_field_entry_add_field (field, 0);
+
+ GtkEntry *entry = ygtk_field_entry_get_field_widget (field, 0);
+ gtk_entry_set_activates_default (entry, TRUE);
if (passwordMode)
- gtk_entry_set_visibility (GTK_ENTRY (getWidget()), FALSE);
+ gtk_entry_set_visibility (entry, FALSE);
- // Signals to know of any text modification
- g_signal_connect (G_OBJECT (getWidget()), "changed",
- G_CALLBACK (text_changed_cb), this);
+ g_signal_connect (G_OBJECT (getWidget()), "field-entry-changed",
+ G_CALLBACK (value_changed_cb), this);
}
- // YTextEntry
+ // YInputField
virtual string value()
{
- return gtk_entry_get_text (GTK_ENTRY (getWidget()));
+ YGtkFieldEntry *field = YGTK_FIELD_ENTRY (getWidget());
+ return ygtk_field_entry_get_field_text (field, 0);
}
virtual void setValue (const string &text)
{
- /* No need to check for valid chars as that's the responsible of the YCP
- application programmer. */
- gtk_entry_set_text (GTK_ENTRY (getWidget()), text.c_str());
+ YGtkFieldEntry *field = YGTK_FIELD_ENTRY (getWidget());
+ ygtk_field_entry_set_field_text (field, 0, text.c_str());
}
- virtual void setInputMaxLength (int nb)
+ void updateProps()
{
- gtk_entry_set_width_chars (GTK_ENTRY (getWidget()), nb);
+ YGtkFieldEntry *field = YGTK_FIELD_ENTRY (getWidget());
+ ygtk_field_entry_setup_field (field, 0, inputMaxLength(), validChars().c_str());
+ }
+
+ virtual void setInputMaxLength (int len)
+ {
+ YInputField::setInputMaxLength (len);
+ updateProps();
}
virtual void setValidChars (const string &validChars)
{
- YGUtils::setFilter (GTK_ENTRY (getWidget()), validChars);
YInputField::setValidChars (validChars);
+ updateProps();
}
- static void text_changed_cb (GtkEditable *editable, YGInputField *pThis)
+ static void value_changed_cb (YGtkFieldEntry *entry, gint field_nb, YGInputField *pThis)
{
pThis->emitEvent (YEvent::ValueChanged);
}
@@ -66,3 +76,210 @@
return new YGInputField (parent, label, passwordMode);
}
+#include "YTimeField.h"
+
+class YGTimeField : public YTimeField, public YGLabeledWidget
+{
+public:
+ YGTimeField (YWidget *parent, const string &label)
+ : YTimeField (NULL, label),
+ YGLabeledWidget (this, parent, label, YD_HORIZ, true,
+ YGTK_TYPE_FIELD_ENTRY, NULL)
+ {
+ IMPL
+ YGtkFieldEntry *field = YGTK_FIELD_ENTRY (getWidget());
+ ygtk_field_entry_add_field (field, ':');
+ ygtk_field_entry_add_field (field, ':');
+ ygtk_field_entry_setup_field (field, 0, 2, "0123456789");
+ ygtk_field_entry_setup_field (field, 1, 2, "0123456789");
+
+ g_signal_connect (G_OBJECT (getWidget()), "field-entry-changed",
+ G_CALLBACK (value_changed_cb), this);
+ }
+
+ // YTimeField
+ virtual void setValue (const string &time)
+ {
+ IMPL
+ char hours[3], mins[3];
+ sscanf (time.c_str(), "%2s:%2s", hours, mins);
+
+ YGtkFieldEntry *entry = YGTK_FIELD_ENTRY (getWidget());
+ ygtk_field_entry_set_field_text (entry, 0, hours);
+ ygtk_field_entry_set_field_text (entry, 1, mins);
+ }
+
+ virtual string value()
+ {
+ IMPL
+ const gchar *hours, *mins;
+ YGtkFieldEntry *entry = YGTK_FIELD_ENTRY (getWidget());
+ hours = ygtk_field_entry_get_field_text (entry, 0);
+ mins = ygtk_field_entry_get_field_text (entry, 1);
+
+ gchar *time = g_strdup_printf ("%02d:%02d:00", atoi (hours), atoi (mins));
+ string str (time);
+ g_free (time);
+ return str;
+ }
+
+ // callbacks
+ static void value_changed_cb (YGtkFieldEntry *entry, gint field_nb,
+ YGTimeField *pThis)
+ { IMPL; pThis->emitEvent (YEvent::ValueChanged); }
+
+ YGWIDGET_IMPL_COMMON
+ YGLABEL_WIDGET_IMPL_SET_LABEL_CHAIN (YTimeField)
+};
+
+YTimeField *YGOptionalWidgetFactory::createTimeField (YWidget *parent, const string &label)
+{
+ IMPL
+ return new YGTimeField (parent, label);
+}
+
+#include "YDateField.h"
+#include "ygtkmenubutton.h"
+
+class YGDateField : public YDateField, public YGLabeledWidget
+{
+GtkWidget *m_calendar, *m_popup_calendar;
+
+public:
+ YGDateField (YWidget *parent, const string &label)
+ : YDateField (NULL, label),
+ YGLabeledWidget (this, parent, label, YD_HORIZ, true, YGTK_TYPE_FIELD_ENTRY, NULL)
+ {
+ IMPL
+ ygtk_field_entry_add_field (getField(), '-');
+ ygtk_field_entry_add_field (getField(), '-');
+ ygtk_field_entry_add_field (getField(), '-');
+ ygtk_field_entry_setup_field (getField(), 0, 4, "0123456789");
+ ygtk_field_entry_setup_field (getField(), 1, 2, "0123456789");
+ ygtk_field_entry_setup_field (getField(), 2, 2, "0123456789");
+
+ GtkWidget *menu_button = ygtk_menu_button_new();
+ m_calendar = gtk_calendar_new();
+ gtk_widget_show (m_calendar);
+ GtkWidget *popup = ygtk_popup_window_new (m_calendar);
+ ygtk_menu_button_set_popup (YGTK_MENU_BUTTON (menu_button), popup);
+ gtk_widget_show_all (popup);
+ gtk_widget_show_all (menu_button);
+
+ gtk_box_pack_start (GTK_BOX (getWidget()), menu_button, FALSE, TRUE, 6);
+
+ g_signal_connect (G_OBJECT (getField()), "field-entry-changed",
+ G_CALLBACK (value_changed_cb), this);
+
+ g_signal_connect (G_OBJECT (m_calendar), "day-selected",
+ G_CALLBACK (calendar_changed_cb), this);
+ g_signal_connect (G_OBJECT (m_calendar), "day-selected-double-click",
+ G_CALLBACK (double_click_cb), popup);
+ }
+
+ inline GtkCalendar *getCalendar()
+ { return GTK_CALENDAR (m_calendar); }
+ inline YGtkFieldEntry *getField()
+ { return YGTK_FIELD_ENTRY (getWidget()); }
+
+ // YDateField
+ virtual void setValue (const string &date)
+ {
+ IMPL
+ char year[5], month[3], day[3];
+ sscanf (date.c_str(), "%4s-%2s-%2s", year, month, day);
+
+ gtk_calendar_select_month (getCalendar(), atoi (month)-1, atoi (year));
+ gtk_calendar_select_day (getCalendar(), atoi (day));
+
+ ygtk_field_entry_set_field_text (getField(), 0, year);
+ ygtk_field_entry_set_field_text (getField(), 1, month);
+ ygtk_field_entry_set_field_text (getField(), 2, day);
+ }
+
+ virtual string value()
+ {
+ IMPL
+ const gchar *year, *month, *day;
+ year = ygtk_field_entry_get_field_text (getField(), 0);
+ month = ygtk_field_entry_get_field_text (getField(), 1);
+ day = ygtk_field_entry_get_field_text (getField(), 2);
+
+ gchar *time = g_strdup_printf ("%04d-%02d-%02d", atoi (year),
+ atoi (month), atoi (day));
+ string str (time);
+ g_free (time);
+ return str;
+ }
+
+ // callbacks
+ static void value_changed_cb (YGtkFieldEntry *entry, gint field_nb,
+ YGDateField *pThis)
+ {
+ IMPL
+ int year, month, day;
+ year = atoi (ygtk_field_entry_get_field_text (pThis->getField(), 0));
+ month = atoi (ygtk_field_entry_get_field_text (pThis->getField(), 1));
+ day = atoi (ygtk_field_entry_get_field_text (pThis->getField(), 2));
+
+ if (day < 1 || day > 31 || month < 1 || month > 12)
+ return; // avoid GtkCalendar warnings
+
+ g_signal_handlers_block_by_func (pThis->getCalendar(),
+ (gpointer) calendar_changed_cb, pThis);
+
+ gtk_calendar_select_month (pThis->getCalendar(), month-1, year);
+ gtk_calendar_select_day (pThis->getCalendar(), day);
+
+ g_signal_handlers_unblock_by_func (pThis->getCalendar(),
+ (gpointer) calendar_changed_cb, pThis);
+
+ pThis->emitEvent (YEvent::ValueChanged);
+ }
+
+ static void calendar_changed_cb (GtkCalendar *calendar, YGDateField *pThis)
+ {
+ IMPL
+ guint year, month, day;
+ gtk_calendar_get_date (calendar, &year, &month, &day);
+ month += 1; // GTK calendar months go from 0 to 11
+
+ gchar *year_str, *month_str, *day_str;
+ year_str = g_strdup_printf ("%d", year);
+ month_str = g_strdup_printf ("%d", month);
+ day_str = g_strdup_printf ("%d", day);
+
+ g_signal_handlers_block_by_func (pThis->getField(),
+ (gpointer) value_changed_cb, pThis);
+
+ YGtkFieldEntry *entry = pThis->getField();
+ ygtk_field_entry_set_field_text (entry, 0, year_str);
+ ygtk_field_entry_set_field_text (entry, 1, month_str);
+ ygtk_field_entry_set_field_text (entry, 2, day_str);
+
+ g_signal_handlers_unblock_by_func (pThis->getField(),
+ (gpointer) value_changed_cb, pThis);
+
+ g_free (year_str);
+ g_free (month_str);
+ g_free (day_str);
+
+ pThis->emitEvent (YEvent::ValueChanged);
+ }
+
+ static void double_click_cb (GtkCalendar *calendar, YGtkPopupWindow *popup)
+ {
+ // close popup
+ gtk_widget_hide (GTK_WIDGET (popup));
+ }
+
+ YGWIDGET_IMPL_COMMON
+ YGLABEL_WIDGET_IMPL_SET_LABEL_CHAIN (YDateField)
+};
+
+YDateField *YGOptionalWidgetFactory::createDateField (YWidget *parent, const string &label)
+{
+ IMPL
+ return new YGDateField (parent, label);
+}
+
Modified: trunk/gtk/unstable-libyui/src/YGIntField.cc
URL: http://svn.opensuse.org/viewcvs/yast/trunk/gtk/unstable-libyui/src/YGIntFie…
==============================================================================
--- trunk/gtk/unstable-libyui/src/YGIntField.cc (original)
+++ trunk/gtk/unstable-libyui/src/YGIntField.cc Thu Dec 6 13:42:24 2007
@@ -112,7 +112,7 @@
public:
YGIntField (YWidget *parent, const string &label, int minValue, int maxValue,
int initialValue)
- : YIntField (parent, label, minValue, maxValue)
+ : YIntField (NULL, label, minValue, maxValue)
, YGSpinBox (this, parent, label, minValue, maxValue, initialValue, false)
{}
@@ -134,7 +134,7 @@
public:
YGSlider (YWidget *parent, const string &label, int minValue, int maxValue,
int initialValue)
- : YSlider (parent, label, minValue, maxValue)
+ : YSlider (NULL, label, minValue, maxValue)
, YGSpinBox (this, parent, label, minValue, maxValue, initialValue, true)
{}
Modified: trunk/gtk/unstable-libyui/src/YGLabel.cc
URL: http://svn.opensuse.org/viewcvs/yast/trunk/gtk/unstable-libyui/src/YGLabel.…
==============================================================================
--- trunk/gtk/unstable-libyui/src/YGLabel.cc (original)
+++ trunk/gtk/unstable-libyui/src/YGLabel.cc Thu Dec 6 13:42:24 2007
@@ -14,7 +14,7 @@
{
public:
YGLabel (YWidget *parent, const string &text, bool heading, bool outputField)
- : YLabel (parent, text, heading, outputField),
+ : YLabel (NULL, text, heading, outputField),
YGWidget (this, parent, true, GTK_TYPE_LABEL, NULL)
{
IMPL
Modified: trunk/gtk/unstable-libyui/src/YGLayout.cc
URL: http://svn.opensuse.org/viewcvs/yast/trunk/gtk/unstable-libyui/src/YGLayout…
==============================================================================
--- trunk/gtk/unstable-libyui/src/YGLayout.cc (original)
+++ trunk/gtk/unstable-libyui/src/YGLayout.cc Thu Dec 6 13:42:24 2007
@@ -22,7 +22,7 @@
public:
YGLayoutBox (YWidget *parent, YUIDimension dim)
- : YLayoutBox (parent, dim),
+ : YLayoutBox (NULL, dim),
YGWidget (this, parent, true,
dim == YD_HORIZ ? YGTK_TYPE_RATIO_HBOX : YGTK_TYPE_RATIO_VBOX, NULL)
{
@@ -36,14 +36,13 @@
g_object_unref (G_OBJECT (m_labels_group));
}
- virtual void addChild (YWidget *ychild)
+ virtual string getDebugLabel() const
+ { return primary() == YD_HORIZ ? "horizontal" : "vertical"; }
+
+ virtual void doAddChild (YWidget *ychild, GtkWidget *container)
{
IMPL
- YLayoutBox::addChild (ychild);
- YGWidget *ygchild = YGWidget::get (ychild);
-
- gtk_container_add (GTK_CONTAINER (getWidget()), ygchild->getLayout());
- sync_stretchable (ychild);
+ YGWidget::doAddChild (ychild, container);
// set labels of YGLabeledWidgets to the same width
// we have to do quite some work due to over-clutter on YCP progs
@@ -60,7 +59,7 @@
}
}
else {
- ygchild = YGWidget::get (ychild);
+ YGWidget *ygchild = YGWidget::get (ychild);
YGLabeledWidget *labeled_child = dynamic_cast <YGLabeledWidget *> (ygchild);
if (labeled_child && labeled_child->orientation() == YD_HORIZ) {
if (!m_labels_group)
@@ -72,6 +71,8 @@
}
}
}
+
+ YGWIDGET_IMPL_CHILD_ADDED (getWidget())
YGWIDGET_IMPL_CHILD_REMOVED (getWidget())
virtual void sync_stretchable (YWidget *ychild)
@@ -108,7 +109,7 @@
public:
YGAlignment (YWidget *parent, YAlignmentType halign, YAlignmentType valign)
- : YAlignment (parent, halign, valign),
+ : YAlignment (NULL, halign, valign),
YGWidget (this, parent, true, GTK_TYPE_ALIGNMENT, NULL)
{
setBorder (0);
@@ -121,26 +122,24 @@
g_object_unref (G_OBJECT (m_background_pixbuf));
}
- virtual void childAdded (YWidget *ychild)
+ virtual void doAddChild (YWidget *ychild, GtkWidget *container)
{
- YGWidget *child = YGWidget::get (ychild);
- gtk_container_add (GTK_CONTAINER (getWidget()), child->getLayout());
+ YGWidget::doAddChild (ychild, container);
/* The padding is used for stuff like making YCP progs nicer for
yast-qt wizard, so it hurts us -- it's disabled. */
//child->setPadding (topMargin(), bottomMargin(),
// leftMargin(), rightMargin());
setMinSize (minWidth(), minHeight());
-
- sync_stretchable (ychild); // alignment will be set here
}
+ YGWIDGET_IMPL_CHILD_ADDED (m_widget)
YGWIDGET_IMPL_CHILD_REMOVED (m_widget)
virtual void sync_stretchable (YWidget *child)
{
IMPL
setAlignment (alignment (YD_HORIZ), alignment (YD_VERT));
- YGWidget::sync_stretchable (m_ywidget);
+ YGWidget::sync_stretchable();
}
void setAlignment (YAlignmentType halign, YAlignmentType valign)
@@ -273,7 +272,7 @@
{
public:
YGEmpty (YWidget *parent)
- : YEmpty (parent),
+ : YEmpty (NULL),
YGWidget (this, parent, true, GTK_TYPE_EVENT_BOX, NULL)
{
setBorder (0);
@@ -295,7 +294,7 @@
{
public:
YGSpacing (YWidget *parent, YUIDimension dim, bool stretchable, YLayoutSize_t size)
- : YSpacing (parent, dim, stretchable, size),
+ : YSpacing (NULL, dim, stretchable, size),
YGWidget (this, parent, true, GTK_TYPE_EVENT_BOX, NULL)
{
setBorder (0);
@@ -314,12 +313,15 @@
#include "YReplacePoint.h"
+//TEMP:
+#include "YPushButton.h"
+
// an empty space that will get replaced
class YGReplacePoint : public YReplacePoint, public YGWidget
{
public:
YGReplacePoint (YWidget *parent)
- : YReplacePoint (parent),
+ : YReplacePoint (NULL),
YGWidget (this, parent, true, GTK_TYPE_EVENT_BOX, NULL)
{
setBorder (0);
@@ -343,7 +345,7 @@
{
public:
YGSquash (YWidget *parent, bool hsquash, bool vsquash)
- : YSquash (parent, hsquash, vsquash),
+ : YSquash (NULL, hsquash, vsquash),
YGWidget (this, parent, true, GTK_TYPE_EVENT_BOX, NULL)
{
setBorder (0);
Modified: trunk/gtk/unstable-libyui/src/YGMenuButton.cc
URL: http://svn.opensuse.org/viewcvs/yast/trunk/gtk/unstable-libyui/src/YGMenuBu…
==============================================================================
--- trunk/gtk/unstable-libyui/src/YGMenuButton.cc (original)
+++ trunk/gtk/unstable-libyui/src/YGMenuButton.cc Thu Dec 6 13:42:24 2007
@@ -14,7 +14,7 @@
{
public:
YGMenuButton (YWidget *parent, const string &label)
- : YMenuButton (parent, label),
+ : YMenuButton (NULL, label),
YGWidget (this, parent, true, YGTK_TYPE_MENU_BUTTON, NULL)
{
IMPL
Modified: trunk/gtk/unstable-libyui/src/YGMultiLineEdit.cc
URL: http://svn.opensuse.org/viewcvs/yast/trunk/gtk/unstable-libyui/src/YGMultiL…
==============================================================================
--- trunk/gtk/unstable-libyui/src/YGMultiLineEdit.cc (original)
+++ trunk/gtk/unstable-libyui/src/YGMultiLineEdit.cc Thu Dec 6 13:42:24 2007
@@ -102,7 +102,7 @@
{
public:
YGMultiLineEdit (YWidget *parent, const string &label)
- : YMultiLineEdit (parent, label)
+ : YMultiLineEdit (NULL, label)
, YGTextView (this, parent, label, true)
{}
@@ -134,7 +134,7 @@
{
public:
YGLogView (YWidget *parent, const string &label, int visibleLines, int maxLines)
- : YLogView (parent, label, visibleLines, maxLines)
+ : YLogView (NULL, label, visibleLines, maxLines)
, YGTextView (this, parent, label, false)
{}
@@ -163,7 +163,7 @@
public:
YGPlainText(YWidget *parent, const string &text)
- : YRichText (parent, text)
+ : YRichText (NULL, text)
, YGTextView (this, parent, string(), false)
{
if (shrinkable())
@@ -189,7 +189,7 @@
{
public:
YGRichText (YWidget *parent, const string &text)
- : YRichText (parent, text)
+ : YRichText (NULL, text)
, YGScrolledWidget (this, parent, true, ygtk_html_wrap_get_type(), NULL)
{
IMPL
Modified: trunk/gtk/unstable-libyui/src/YGPackageSelector.cc
URL: http://svn.opensuse.org/viewcvs/yast/trunk/gtk/unstable-libyui/src/YGPackag…
==============================================================================
--- trunk/gtk/unstable-libyui/src/YGPackageSelector.cc (original)
+++ trunk/gtk/unstable-libyui/src/YGPackageSelector.cc Thu Dec 6 13:42:24 2007
@@ -10,6 +10,7 @@
#include "YGi18n.h"
#include "YGDialog.h"
+#if 1
#include "ygtkwizard.h"
#include "ygtkfindentry.h"
#include "ygtkhtmlwrap.h"
@@ -1381,9 +1382,10 @@
public:
YGPackageSelector (YWidget *parent, long mode)
- : YPackageSelector (parent, mode),
+ : YPackageSelector (NULL, mode),
YGWidget (this, parent, true, YGTK_TYPE_WIZARD, NULL)
{
+fprintf (stderr, "YGPackageSelector()\n");
setBorder (0);
YGDialog *dialog = YGDialog::currentDialog();
dialog->setCloseCallback (confirm_cb, this);
@@ -1392,6 +1394,7 @@
gtk_window_resize (window, GTK_WIDGET (window)->allocation.width,
MAX (580, GTK_WIDGET (window)->allocation.height));
+fprintf (stderr, "wizard setup\n");
YGtkWizard *wizard = YGTK_WIZARD (getWidget());
ygtk_wizard_set_header_icon (wizard, window,
THEMEDIR "/icons/32x32/apps/yast-software.png");
@@ -1400,18 +1403,22 @@
_("TO WRITE")
);
+fprintf (stderr, "buttons strings\n");
ygtk_wizard_set_abort_button_label (wizard, _("_Cancel"));
- ygtk_wizard_set_abort_button_id (wizard, g_strdup ("cancel"), g_free);
+ ygtk_wizard_set_abort_button_str_id (wizard, "cancel");
ygtk_wizard_set_back_button_label (wizard, "");
ygtk_wizard_set_next_button_label (wizard, _("_Accept"));
- ygtk_wizard_set_next_button_id (wizard, g_strdup ("accept"), g_free);
+ ygtk_wizard_set_next_button_str_id (wizard, "accept");
g_signal_connect (G_OBJECT (getWidget()), "action-triggered",
G_CALLBACK (wizard_action_cb), this);
+fprintf (stderr, "create package selector\n");
m_package_selector = new PackageSelector();
gtk_container_add (GTK_CONTAINER (wizard), m_package_selector->getWidget());
+fprintf (stderr, "ypp::set interface()\n");
Ypp::get()->setInterface (this);
+fprintf (stderr, "done()\n");
}
virtual ~YGPackageSelector()
@@ -1425,7 +1432,9 @@
gint id_type, YGPackageSelector *pThis)
{
IMPL
+fprintf (stderr, "wizard action\n");
const gchar *action = (gchar *) id;
+fprintf (stderr, "action: %s\n", action);
if (!strcmp (action, "accept")) {
y2milestone ("Closing PackageSelector with 'accept'");
@@ -1674,7 +1683,6 @@
gtk_container_add (GTK_CONTAINER (scroll), view);
gtk_container_add (GTK_CONTAINER (GTK_DIALOG (dialog)->vbox), scroll);
-
#if 0
// version that uses viewport, labels and radio buttons -- unfortunately,
// gtk+ enforces that one radio button per group to be selected -- we don't
@@ -1748,6 +1756,20 @@
YGWIDGET_IMPL_COMMON
};
+#else
+#include "YPackageSelector.h"
+class YGPackageSelector : public YPackageSelector, public YGWidget
+{
+public:
+ YGPackageSelector (YWidget *parent, long mode)
+ : YPackageSelector (NULL, mode),
+ YGWidget (this, parent, true, GTK_TYPE_EVENT_BOX, NULL)
+ {
+ }
+ YGWIDGET_IMPL_COMMON
+};
+#endif
+
YPackageSelector *YGWidgetFactory::createPackageSelector (YWidget *parent, long mode)
{
/* if (opt.youMode.value())
Modified: trunk/gtk/unstable-libyui/src/YGProgressBar.cc
URL: http://svn.opensuse.org/viewcvs/yast/trunk/gtk/unstable-libyui/src/YGProgre…
==============================================================================
--- trunk/gtk/unstable-libyui/src/YGProgressBar.cc (original)
+++ trunk/gtk/unstable-libyui/src/YGProgressBar.cc Thu Dec 6 13:42:24 2007
@@ -13,16 +13,13 @@
{
public:
YGProgressBar (YWidget *parent, const string &label, int maxValue)
- : YProgressBar (parent, label, maxValue)
+ : YProgressBar (NULL, label, maxValue)
// NOTE: its label widget is positionated at the vertical, because its label
// may change often and so will its size, which will look odd (we may want
// to make the label widget to only grow).
, YGLabeledWidget (this, parent, label, YD_VERT, true,
GTK_TYPE_PROGRESS_BAR, NULL)
- {
- }
-
- virtual ~YGProgressBar() {}
+ {}
// YProgressBar
virtual void setValue (int value)
@@ -53,7 +50,7 @@
public:
YGDownloadProgress (YWidget *parent, const string &label,
const string &filename, YFileSize_t expectedFileSize)
- : YDownloadProgress (parent, label, filename, expectedFileSize)
+ : YDownloadProgress (NULL, label, filename, expectedFileSize)
, YGLabeledWidget (this, parent, label, YD_HORIZ, true,
GTK_TYPE_PROGRESS_BAR, NULL)
{
@@ -98,7 +95,7 @@
{
public:
YGMultiProgressMeter (YWidget *parent, YUIDimension dim, const vector<float> &maxValues)
- : YMultiProgressMeter (parent, dim, maxValues)
+ : YMultiProgressMeter (NULL, dim, maxValues)
, YGWidget (this, parent, true,
horizontal() == YD_HORIZ ? YGTK_TYPE_RATIO_HBOX : YGTK_TYPE_RATIO_VBOX, NULL)
{
Modified: trunk/gtk/unstable-libyui/src/YGPushButton.cc
URL: http://svn.opensuse.org/viewcvs/yast/trunk/gtk/unstable-libyui/src/YGPushBu…
==============================================================================
--- trunk/gtk/unstable-libyui/src/YGPushButton.cc (original)
+++ trunk/gtk/unstable-libyui/src/YGPushButton.cc Thu Dec 6 13:42:24 2007
@@ -15,7 +15,7 @@
public:
YGPushButton (YWidget *parent, const string &label)
- : YPushButton (parent, label),
+ : YPushButton (NULL, label),
YGWidget (this, parent, true, GTK_TYPE_BUTTON, "can-default", TRUE, NULL)
{
IMPL
Modified: trunk/gtk/unstable-libyui/src/YGRadioButton.cc
URL: http://svn.opensuse.org/viewcvs/yast/trunk/gtk/unstable-libyui/src/YGRadioB…
==============================================================================
--- trunk/gtk/unstable-libyui/src/YGRadioButton.cc (original)
+++ trunk/gtk/unstable-libyui/src/YGRadioButton.cc Thu Dec 6 13:42:24 2007
@@ -39,7 +39,7 @@
{
public:
YGRadioButton (YWidget *parent, const std::string &label, bool isChecked)
- : YRadioButton (parent, label),
+ : YRadioButton (NULL, label),
YGWidget (this, parent, true, getCheckRadioButtonType(), NULL)
{
IMPL
@@ -73,10 +73,11 @@
virtual void setValue (bool checked)
{
IMPL
+ fprintf (stderr, "setValue: %d to %s\n", checked, getDebugLabel().c_str());
g_signal_handlers_block_by_func (getWidget(), (gpointer) toggled_cb, this);
- if (value())
- buttonGroup()->uncheckOtherButtons (this);
+ if (checked)
+ buttonGroup()->uncheckOtherButtons ((YRadioButton *) this);
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (getWidget()), checked);
g_signal_handlers_unblock_by_func (getWidget(), (gpointer) toggled_cb, this);
@@ -89,15 +90,20 @@
static void toggled_cb (GtkButton *button, YGRadioButton *pThis)
{
IMPL
+fprintf(stderr, "toggled\n");
if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (button)))
- pThis->buttonGroup()->uncheckOtherButtons (pThis);
+{
+fprintf(stderr, "uncheck others\n");
+ pThis->buttonGroup()->uncheckOtherButtons ((YRadioButton *) pThis);
+// pThis->emitEvent (YEvent::ValueChanged);
+}
else {
+ // leave it active
g_signal_handlers_block_by_func (button, (gpointer) toggled_cb, pThis);
+fprintf(stderr, "set active\n");
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (button), TRUE);
g_signal_handlers_unblock_by_func (button, (gpointer) toggled_cb, pThis);
}
-
- pThis->emitEvent (YEvent::ValueChanged);
}
};
@@ -114,7 +120,7 @@
{
public:
YGRadioButtonGroup(YWidget *parent)
- : YRadioButtonGroup (parent),
+ : YRadioButtonGroup (NULL),
YGWidget (this, parent, true, GTK_TYPE_EVENT_BOX, NULL)
{}
@@ -136,7 +142,7 @@
public:
YGCheckBox(YWidget *parent, const string &label, bool isChecked)
- : YCheckBox (parent, label),
+ : YCheckBox (NULL, label),
YGWidget (this, parent, true, GTK_TYPE_CHECK_BUTTON, NULL)
{
IMPL
Modified: trunk/gtk/unstable-libyui/src/YGSelectionModel.cc
URL: http://svn.opensuse.org/viewcvs/yast/trunk/gtk/unstable-libyui/src/YGSelect…
==============================================================================
--- trunk/gtk/unstable-libyui/src/YGSelectionModel.cc (original)
+++ trunk/gtk/unstable-libyui/src/YGSelectionModel.cc Thu Dec 6 13:42:24 2007
@@ -20,7 +20,7 @@
}
YGSelectionModel::~YGSelectionModel()
-{ g_object_unref (G_OBJECT (model)); }
+{ g_object_unref (G_OBJECT (m_model)); }
void YGSelectionModel::createModel (const vector <GType> &types)
{
@@ -32,19 +32,17 @@
types_array[colsNb-1] = G_TYPE_POINTER;
if (isTree)
- model = GTK_TREE_MODEL (gtk_tree_store_newv (colsNb, types_array));
+ m_model = GTK_TREE_MODEL (gtk_tree_store_newv (colsNb, types_array));
else
- model = GTK_TREE_MODEL (gtk_list_store_newv (colsNb, types_array));
- setModel (model);
+ m_model = GTK_TREE_MODEL (gtk_list_store_newv (colsNb, types_array));
}
GtkTreeModel *YGSelectionModel::getModel()
-{ return model; }
-
+{ return m_model; }
GtkListStore *YGSelectionModel::getListStore()
-{ return model ? GTK_LIST_STORE (model) : NULL; }
+{ return m_model ? GTK_LIST_STORE (m_model) : NULL; }
GtkTreeStore *YGSelectionModel::getTreeStore()
-{ return model ? GTK_TREE_STORE (model) : NULL; }
+{ return m_model ? GTK_TREE_STORE (m_model) : NULL; }
bool YGSelectionModel::isEmpty()
{
@@ -82,13 +80,28 @@
if (!gtk_tree_model_get_iter_first (getModel(), iter))
return false;
- do {
- gpointer ptr;
- gtk_tree_model_get (getModel(), iter, getPtrCol(), &ptr, -1);
- if (ptr == item)
- return true;
- } while (gtk_tree_model_iter_next (getModel(), iter));
- return false;
+ struct inner {
+ static bool getIter (GtkTreeModel *model, int col, YItem *item, GtkTreeIter *iter)
+ {
+ gpointer ptr;
+ gtk_tree_model_get (model, iter, col, &ptr, -1);
+ if (((YItem *) ptr)->index() == item->index())
+ return true;
+
+ GtkTreeIter child;
+ if (gtk_tree_model_iter_children (model, &child, iter)) {
+ if (getIter (model, col, item, &child)) {
+ *iter = child;
+ return true;
+ }
+ }
+ if (gtk_tree_model_iter_next (model, iter))
+ return getIter (model, col, item, iter);
+ return false;
+ }
+ };
+
+ return inner::getIter (getModel(), getPtrCol(), item, iter);
}
void YGSelectionModel::implFocusItem (YItem *item)
Modified: trunk/gtk/unstable-libyui/src/YGSelectionModel.h
URL: http://svn.opensuse.org/viewcvs/yast/trunk/gtk/unstable-libyui/src/YGSelect…
==============================================================================
--- trunk/gtk/unstable-libyui/src/YGSelectionModel.h (original)
+++ trunk/gtk/unstable-libyui/src/YGSelectionModel.h Thu Dec 6 13:42:24 2007
@@ -23,9 +23,7 @@
YGSelectionModel (bool ordinaryModel, bool isTree);
virtual ~YGSelectionModel();
- // the model may not necessarly be created at construction
GtkTreeModel *getModel();
- virtual void setModel (GtkTreeModel *model) = 0;
void createModel (const vector <GType> &types);
void doAddItem (YItem *item);
@@ -47,7 +45,7 @@
protected:
void implFocusItem (YItem *item);
private:
- GtkTreeModel *model;
+ GtkTreeModel *m_model;
bool isTree;
GtkListStore *getListStore();
GtkTreeStore *getTreeStore();
Modified: trunk/gtk/unstable-libyui/src/YGTable.cc
URL: http://svn.opensuse.org/viewcvs/yast/trunk/gtk/unstable-libyui/src/YGTable.…
==============================================================================
--- trunk/gtk/unstable-libyui/src/YGTable.cc (original)
+++ trunk/gtk/unstable-libyui/src/YGTable.cc Thu Dec 6 13:42:24 2007
@@ -27,14 +27,15 @@
if (ordinaryModel) {
addColumn (G_TYPE_STRING, "", YAlignUnchanged, YGSelectionModel::LABEL_COLUMN);
addColumn (GDK_TYPE_PIXBUF, "", YAlignUnchanged, YGSelectionModel::ICON_COLUMN);
+ gtk_tree_view_set_model (getView(), getModel());
}
gtk_tree_view_set_headers_visible (GTK_TREE_VIEW (getWidget()), FALSE);
/* Yast tools expect the user to be unable to un-select the row. They
generally don't check to see if the returned value is -1. So, just
disallow un-selection. */
- gtk_tree_selection_set_mode (gtk_tree_view_get_selection (
- GTK_TREE_VIEW (getWidget())), GTK_SELECTION_BROWSE);
+ GtkTreeSelection *selection = gtk_tree_view_get_selection (getView());
+ gtk_tree_selection_set_mode (selection, GTK_SELECTION_BROWSE);
// let the derivates do the event hooks. They have subtile differences.
}
@@ -49,10 +50,10 @@
GtkTreeViewColumn *column = 0;
// The allignment of the column items
- gfloat xalign = 0.0;
+ gfloat xalign = -1;
switch (header_align) {
- case YAlignUnchanged:
case YAlignBegin:
+ xalign = 0.0;
break;
case YAlignCenter:
xalign = 0.5;
@@ -60,11 +61,13 @@
case YAlignEnd:
xalign = 1.0;
break;
+ case YAlignUnchanged:
+ break;
}
+ GtkCellRenderer *renderer = 0;
if (type == G_TYPE_STRING) {
- GtkCellRenderer *renderer = gtk_cell_renderer_text_new();
- g_object_set (renderer, "xalign", xalign, NULL);
+ renderer = gtk_cell_renderer_text_new();
// set the last column, the expandable one, as wrapable
if (isEllipsize)
g_object_set (renderer, "ellipsize", PANGO_ELLIPSIZE_END, NULL);
@@ -72,15 +75,13 @@
renderer, "text", col_nb, NULL);
}
else if (type == GDK_TYPE_PIXBUF) {
- GtkCellRenderer *renderer = gtk_cell_renderer_pixbuf_new();
- g_object_set (renderer, "xalign", xalign, NULL);
+ renderer = gtk_cell_renderer_pixbuf_new();
column = gtk_tree_view_column_new_with_attributes (header.c_str(),
renderer, "pixbuf", col_nb, NULL);
}
else if (type == G_TYPE_BOOLEAN) { // toggle button
- GtkCellRenderer *renderer = gtk_cell_renderer_toggle_new();
+ renderer = gtk_cell_renderer_toggle_new();
g_object_set_data (G_OBJECT (renderer), "column", GINT_TO_POINTER (col_nb));
- g_object_set (renderer, "xalign", xalign, NULL);
column = gtk_tree_view_column_new_with_attributes (header.c_str(),
renderer, "active", col_nb, NULL);
@@ -90,6 +91,9 @@
else
g_error ("YGTable: no support for column of given type");
+ if (renderer && xalign != -1)
+ g_object_set (renderer, "xalign", xalign, NULL);
+
gtk_tree_view_column_set_resizable (column, TRUE);
gtk_tree_view_append_column (getView(), column);
}
@@ -190,15 +194,27 @@
class YGTable : public YTable, public YGTableView
{
public:
- YGTable (YWidget *parent, YTableHeader *header)
- : YTable (parent, header)
+ YGTable (YWidget *parent, YTableHeader *_header)
+ : YTable (NULL, _header)
, YGTableView (this, parent, string(), false, false)
{
IMPL
- gtk_tree_view_set_headers_visible (getView(), FALSE);
+ gtk_tree_view_set_headers_visible (getView(), TRUE);
if (columns() >= 3)
gtk_tree_view_set_rules_hint (getView(), TRUE);
+ vector <GType> types;
+ types.assign (columns(), G_TYPE_STRING);
+/* for (int i = 0; i < columns(); i++)
+ if (item->hasIconName (i))
+ types[i] = GDK_TYPE_PIXBUF;*/
+ createModel (types);
+ for (int i = 0; i < columns(); i++) {
+ bool ellipsize = columns() >= 3 && i == columns()-1;
+ addColumn (types[i], header (i), alignment (i), i, ellipsize);
+ }
+ gtk_tree_view_set_model (getView(), getModel());
+
g_signal_connect (G_OBJECT (getWidget()), "row-activated",
G_CALLBACK (activated_cb), (YGTableView*) this);
if (immediateMode())
@@ -217,25 +233,12 @@
{
YTableItem *item = dynamic_cast <YTableItem *> (_item);
if (item) {
- if (!getModel()) {
- vector <GType> types;
- types.assign (columns(), G_TYPE_STRING);
- for (int i = 0; i < columns(); i++)
- if (item->hasIconName (i))
- types[i] = GDK_TYPE_PIXBUF;
- createModel (types);
- for (int i = 0; i < columns(); i++) {
- bool ellipsize = columns() >= 3 && i == columns()-1;
- addColumn (types[i], header (i), alignment (i), i, ellipsize);
- }
- }
-
GtkTreeIter iter;
addRow (&iter, _item);
for (int i = 0; i < columns(); i++) {
- if (item->hasIconName (i))
+/* if (item->hasIconName (i))
setCellIcon (&iter, i, item->iconName (i));
- else
+ else*/
setCellLabel (&iter, i, item->label (i));
}
}
@@ -272,7 +275,7 @@
{
public:
YGSelectionBox (YWidget *parent, const string &label)
- : YSelectionBox (parent, label),
+ : YSelectionBox (NULL, label),
YGTableView (this, parent, label, true, false)
{
g_signal_connect (G_OBJECT (getWidget()), "row-activated",
@@ -301,7 +304,7 @@
{
public:
YGMultiSelectionBox (YWidget *parent, const string &label)
- : YMultiSelectionBox (parent, label),
+ : YMultiSelectionBox (NULL, label),
YGTableView (this, parent, label, false, false)
{
vector <GType> types;
@@ -312,6 +315,7 @@
addColumn (G_TYPE_BOOLEAN, "", YAlignUnchanged, 0);
addColumn (GDK_TYPE_PIXBUF, "", YAlignUnchanged, 1);
addColumn (G_TYPE_STRING, "", YAlignUnchanged, 2);
+ gtk_tree_view_set_model (getView(), getModel());
g_signal_connect (G_OBJECT (getWidget()), "cursor-changed",
G_CALLBACK (selected_cb), (YGTableView*) this);
@@ -385,7 +389,7 @@
{
public:
YGTree (YWidget *parent, const string &label)
- : YTree (parent, label)
+ : YTree (NULL, label)
, YGTableView (this, parent, label, false, true)
{
// Events
Modified: trunk/gtk/unstable-libyui/src/YGUI.cc
URL: http://svn.opensuse.org/viewcvs/yast/trunk/gtk/unstable-libyui/src/YGUI.cc?…
==============================================================================
--- trunk/gtk/unstable-libyui/src/YGUI.cc (original)
+++ trunk/gtk/unstable-libyui/src/YGUI.cc Thu Dec 6 13:42:24 2007
@@ -112,6 +112,7 @@
void YGUI::idleLoop (int fd_ycp)
{
IMPL
+//fprintf (stderr, "idleLoop()\n");
// The rational for this is that we need somewhere to run
// the magic 'main' thread, that can process thread unsafe
// incoming CORBA messages for us
@@ -130,6 +131,7 @@
g_source_remove (watch_tag);
g_io_channel_unref (wakeup);
+//fprintf (stderr, "no more idle\n");
}
static gboolean user_input_timeout_cb (YGUI *pThis)
@@ -150,7 +152,8 @@
YEvent *YGUI::waitInput (unsigned long timeout_ms, bool block)
{
IMPL
- if (!YDialog::currentDialog())
+//fprintf (stderr, "waitInput()\n");
+ if (!YDialog::currentDialog (false))
return NULL;
if (block)
@@ -180,6 +183,7 @@
if (block) // if YCP keeps working for more than X time, set busy cursor
busy_timeout = g_timeout_add (BUSY_CURSOR_TIMEOUT, busy_timeout_cb, this);
+//fprintf (stderr, "returning event: %s\n", !event ? "(none)" : YEvent::toString (event->eventType()));
return event;
}
@@ -207,9 +211,9 @@
int YGUI::getDefaultWidth()
{
if (!m_default_size.width) {
- if (m_fullscreen)
+/* if (m_fullscreen)
m_default_size.width = getDisplayWidth();
- else
+ else*/
m_default_size.width = MIN (600, getDisplayWidth());
}
return m_default_size.width;
@@ -218,9 +222,9 @@
int YGUI::getDefaultHeight()
{
if (!m_default_size.height) {
- if (m_fullscreen)
+/* if (m_fullscreen)
m_default_size.height = getDisplayHeight();
- else
+ else*/
m_default_size.height = MIN (450, getDisplayHeight());
}
return m_default_size.height;
Modified: trunk/gtk/unstable-libyui/src/YGUI.h
URL: http://svn.opensuse.org/viewcvs/yast/trunk/gtk/unstable-libyui/src/YGUI.h?r…
==============================================================================
--- trunk/gtk/unstable-libyui/src/YGUI.h (original)
+++ trunk/gtk/unstable-libyui/src/YGUI.h Thu Dec 6 13:42:24 2007
@@ -44,12 +44,12 @@
bool with_threads, const char *macro_file);
virtual ~YGUI();
- static YGUI *ui() { return (YGUI *)YUI::ui(); }
+ static YGUI *ui() { return (YGUI *) YUI::ui(); }
protected:
- virtual YWidgetFactory * createWidgetFactory();
- virtual YOptionalWidgetFactory * createOptionalWidgetFactory();
- virtual YApplication * createApplication();
+ virtual YWidgetFactory *createWidgetFactory();
+ virtual YOptionalWidgetFactory *createOptionalWidgetFactory();
+ virtual YApplication *createApplication();
public:
YEvent *waitInput (unsigned long timeout_ms, bool block);
@@ -129,7 +129,7 @@
public:
// Helpers for internal use [ visibility hidden ]
int getDefaultSize (YUIDimension dim);
- bool setFullscreen() const { return m_fullscreen || !m_have_wm; }
+ bool setFullscreen() const { return m_fullscreen; }
bool hasWM() const { return m_have_wm; }
bool unsetBorder() const { return m_no_border; }
};
@@ -225,7 +225,6 @@
virtual bool hasSimplePatchSelector() IMPL_RET (false)
virtual YWidget *createSimplePatchSelector (YWidget *parent, long modeFlags)
IMPL_RET (NULL)
-
virtual bool hasPatternSelector() IMPL_RET (false)
virtual YWidget *createPatternSelector (YWidget *parent, long modeFlags)
IMPL_RET (NULL)
Modified: trunk/gtk/unstable-libyui/src/YGWidget.cc
URL: http://svn.opensuse.org/viewcvs/yast/trunk/gtk/unstable-libyui/src/YGWidget…
==============================================================================
--- trunk/gtk/unstable-libyui/src/YGWidget.cc (original)
+++ trunk/gtk/unstable-libyui/src/YGWidget.cc Thu Dec 6 13:42:24 2007
@@ -38,15 +38,16 @@
gtk_container_add (GTK_CONTAINER (m_adj_size), m_widget);
}
-fprintf (stderr, "set widget rep\n");
- ywidget->setWidgetRep ((void *) this);
- if (yparent)
- ywidget->setParent (yparent);
-
// Split by two so that with another widget it will have full border...
setBorder (DEFAULT_BORDER / 2);
if (_show)
show();
+
+ ywidget->setWidgetRep ((void *) this);
+ if (yparent) {
+ ywidget->setParent (yparent);
+ yparent->addChild (ywidget);
+ }
}
YGWidget::~YGWidget()
@@ -63,7 +64,6 @@
YGWidget *YGWidget::get (YWidget *ywidget)
{
- g_assert (ywidget != NULL);
g_assert (ywidget->widgetRep() != NULL);
return (YGWidget *) ywidget->widgetRep();
}
@@ -79,6 +79,26 @@
gtk_widget_set_sensitive (getWidget(), enabled);
}
+void YGWidget::doAddChild (YWidget *ychild, GtkWidget *container)
+{
+ GtkWidget *child = YGWidget::get (ychild)->getLayout();
+ gtk_container_add (GTK_CONTAINER (container), child);
+}
+
+void YGWidget::doRemoveChild (YWidget *ychild, GtkWidget *container)
+{
+ /* Note: removeChild() is generally a result of a widget being removed as it
+ will remove itself from the parent. But YGWidget deconstructor would run
+ before the YWidget one, as that's the order we have been using, so we
+ can't use it, we can't retrieve the GTK widget then. However, this is a
+ non-issue, as ~YGWidget will destroy the widget, and GTK will remove it
+ from the parent. */
+ if (!ychild->beingDestroyed()) {
+ GtkWidget *child = YGWidget::get (ychild)->getLayout();
+ gtk_container_remove (GTK_CONTAINER (container), child);
+ }
+}
+
void YGWidget::emitEvent(YEvent::EventReason reason, bool if_notify,
bool if_not_pending, bool immediate)
{
@@ -132,7 +152,6 @@
IMPL
YWidget *parent = m_ywidget->parent();
if (parent)
- // tell parent to sync too!
YGWidget::get (parent)->sync_stretchable (m_ywidget);
}
Modified: trunk/gtk/unstable-libyui/src/YGWidget.h
URL: http://svn.opensuse.org/viewcvs/yast/trunk/gtk/unstable-libyui/src/YGWidget…
==============================================================================
--- trunk/gtk/unstable-libyui/src/YGWidget.h (original)
+++ trunk/gtk/unstable-libyui/src/YGWidget.h Thu Dec 6 13:42:24 2007
@@ -34,6 +34,8 @@
// for YWidget
virtual bool doSetKeyboardFocus();
virtual void doSetEnabling (bool enabled);
+ virtual void doAddChild (YWidget *child, GtkWidget *container);
+ virtual void doRemoveChild (YWidget *child, GtkWidget *container);
// Event handling
void emitEvent(YEvent::EventReason reason, bool if_notify = true,
@@ -78,7 +80,7 @@
#define YGWIDGET_IMPL_USE_BOLD(ParentClass) \
virtual void setUseBoldFont (bool useBold) { \
PangoWeight weight = useBold ? PANGO_WEIGHT_BOLD : PANGO_WEIGHT_NORMAL; \
- YGUtils::setWidgetFont (getWidget(), weight, PANGO_SCALE_MEDIUM); \
+ YGUtils::setWidgetFont (getWidget(), weight, PANGO_SCALE_MEDIUM); \
ParentClass::setUseBoldFont (useBold); \
}
@@ -86,15 +88,13 @@
#define YGWIDGET_IMPL_CHILD_ADDED(container) \
virtual void addChild (YWidget *ychild) { \
YWidget::addChild (ychild); \
- GtkWidget *child = YGWidget::get (ychild)->getLayout(); \
- gtk_container_add (GTK_CONTAINER (container), child); \
- sync_stretchable(); \
+ doAddChild (ychild, container); \
+ sync_stretchable (ychild); \
}
-#define YGWIDGET_IMPL_CHILD_REMOVED(container) \
- virtual void removeChild (YWidget *ychild) { \
- YWidget::removeChild (ychild); \
- GtkWidget *child = YGWidget::get (ychild)->getLayout(); \
- gtk_container_remove (GTK_CONTAINER (container), child); \
+#define YGWIDGET_IMPL_CHILD_REMOVED(container) \
+ virtual void removeChild (YWidget *ychild) { \
+ YWidget::removeChild (ychild); \
+ doRemoveChild (ychild, container); \
}
/* This is a convenience class that allows for a label next to the
Modified: trunk/gtk/unstable-libyui/src/YGWizard.cc
URL: http://svn.opensuse.org/viewcvs/yast/trunk/gtk/unstable-libyui/src/YGWizard…
==============================================================================
--- trunk/gtk/unstable-libyui/src/YGWizard.cc (original)
+++ trunk/gtk/unstable-libyui/src/YGWizard.cc Thu Dec 6 13:42:24 2007
@@ -14,6 +14,13 @@
#include "YReplacePoint.h"
#include "YGDialog.h"
+
+// FIXME: wizard events need to be ported
+// We'll probably want to also make YGtkWizard buttons actual YGPushButtons...
+// (let's just create them and pass button->getWidget() to the wizard...)
+// (or let's just improve on the wrapper and id.)
+
+
class YGWizard : public YWizard, public YGWidget
{
bool m_verboseCommands;
@@ -33,7 +40,7 @@
of id change. */
YGWButton (YWidget *parent, GtkWidget *widget, const std::string &label)
: YPushButton (parent, label)
- { m_widget = widget; setLabel (label); }
+ { setWidgetRep (NULL); m_widget = widget; setLabel (label); }
void setLabel (const string &label) {
string str = YGUtils::mapKBAccel (label.c_str());
@@ -56,7 +63,7 @@
GtkWidget *m_widget;
};
- YGWButton *m_back_button, *m_abort_button, *m_next_button;
+ YGWButton *m_back_button, *m_abort_button, *m_next_button, *m_notes_button;
// release notes button would be a little more hassle to support; yast-qt
// doesn't support it too anyway.
@@ -64,7 +71,7 @@
YGWizard (YWidget *parent, const string &backButtonLabel,
const string &abortButtonLabel, const string &nextButtonLabel,
YWizardMode wizardMode)
- : YWizard (parent, backButtonLabel, abortButtonLabel, nextButtonLabel, wizardMode)
+ : YWizard (NULL, backButtonLabel, abortButtonLabel, nextButtonLabel, wizardMode)
, YGWidget (this, parent, true, YGTK_TYPE_WIZARD, NULL)
{
IMPL
@@ -97,9 +104,15 @@
ygtk_wizard_enable_tree (getWizard());
//** Setting the bottom buttons
- m_back_button = new YGWButton (this, getWizard()->m_back_button, backButtonLabel);
+ m_back_button = new YGWButton (this, getWizard()->m_back_button, backButtonLabel);
m_abort_button = new YGWButton (this, getWizard()->m_abort_button, abortButtonLabel);
- m_next_button = new YGWButton (this, getWizard()->m_next_button, nextButtonLabel);
+ m_next_button = new YGWButton (this, getWizard()->m_next_button, nextButtonLabel);
+ m_notes_button = new YGWButton (this, getWizard()->m_release_notes_button, string());
+
+ ygtk_wizard_set_back_button_ptr_id (getWizard(), (gpointer) m_back_button);
+ ygtk_wizard_set_next_button_ptr_id (getWizard(), (gpointer) m_next_button);
+ ygtk_wizard_set_abort_button_ptr_id (getWizard(), (gpointer) m_abort_button);
+ ygtk_wizard_set_release_notes_button_ptr_id (getWizard(), (gpointer) m_notes_button);
//** All event are sent through this signal together with an id
g_signal_connect (G_OBJECT (getWidget()), "action-triggered",
@@ -240,8 +253,8 @@
virtual void showReleaseNotesButton (const string &label, const string &id)
{
string str = YGUtils::mapKBAccel (label.c_str());
- ygtk_wizard_set_release_notes_button_label (getWizard(), label.c_str(),
- g_strdup (id.c_str()), free_string_cb);
+ ygtk_wizard_set_release_notes_button_label (getWizard(), str.c_str());
+ ygtk_wizard_set_release_notes_button_str_id (getWizard(), id.c_str());
}
virtual void hideReleaseNotesButton()
@@ -259,12 +272,15 @@
if ((GType) id_type == G_TYPE_STRING)
YGUI::ui()->sendEvent (new YMenuEvent ((char *) id));
else
- YGUI::ui()->sendEvent (new YMenuEvent (*((YCPValue *) id)));
+ YGUI::ui()->sendEvent (new YWidgetEvent ((YWidget *) id, YEvent::Activated));
}
- static void free_string_cb (gpointer data)
- { g_free (data); }
-
+ virtual void doAddChild (YWidget *ychild, GtkWidget *container)
+ {
+ if (ychild->widgetRep())
+ // don't actually add the button wrappers
+ YGWidget::doAddChild (ychild, container);
+ }
YGWIDGET_IMPL_COMMON
YGWIDGET_IMPL_CHILD_ADDED (getWidget())
Modified: trunk/gtk/unstable-libyui/src/ygtkfieldentry.c
URL: http://svn.opensuse.org/viewcvs/yast/trunk/gtk/unstable-libyui/src/ygtkfiel…
==============================================================================
--- trunk/gtk/unstable-libyui/src/ygtkfieldentry.c (original)
+++ trunk/gtk/unstable-libyui/src/ygtkfieldentry.c Thu Dec 6 13:42:24 2007
@@ -81,19 +81,38 @@
g_signal_emit (fields, filter_entry_signal, 0, nb);
}
-void ygtk_field_entry_add_field (YGtkFieldEntry *fields, gchar separator,
- guint max_length, const gchar *valid_chars)
+static guint ygtk_field_entry_length (YGtkFieldEntry *fields)
{
+ guint length;
+ GList *children = gtk_container_get_children (GTK_CONTAINER (fields));
+ length = g_list_length (children);
+ g_list_free (children);
+ return length;
+}
+
+static inline guint child_to_index (YGtkFieldEntry *fields, guint child_i)
+{ return child_i / 2; }
+static inline guint index_to_child (YGtkFieldEntry *fields, guint index)
+{ return index * 2; }
+
+GtkEntry *ygtk_field_entry_get_field_widget (YGtkFieldEntry *fields, guint index)
+{
+ GtkEntry *entry;
+ GList *children = gtk_container_get_children (GTK_CONTAINER (fields));
+ entry = g_list_nth_data (children, index_to_child (fields, index));
+ g_list_free (children);
+ return entry;
+}
+guint ygtk_field_entry_add_field (YGtkFieldEntry *fields, gchar separator)
+{
+ guint new_index = child_to_index (fields, ygtk_field_entry_length (fields));
+
GtkWidget *label = 0, *entry;
- if (fields->use_separator) {
+ if (new_index > 0) {
const gchar str[2] = { separator, '\0' };
label = gtk_label_new (str);
}
entry = gtk_entry_new();
- gtk_entry_set_max_length (GTK_ENTRY (entry), max_length);
- gtk_entry_set_width_chars (GTK_ENTRY (entry), (max_length == 0) ? -1 : max_length);
- ygutils_setFilter (GTK_ENTRY (entry), valid_chars);
-
g_signal_connect (G_OBJECT (entry), "insert-text",
G_CALLBACK (ygtk_field_entry_insert_text), fields);
g_signal_connect (G_OBJECT (entry), "move-cursor",
@@ -103,25 +122,29 @@
G_CALLBACK (ygtk_field_entry_entry_changed), fields);
GtkBox *box = GTK_BOX (fields);
- if (label)
+ if (label) {
gtk_box_pack_start (box, label, FALSE, FALSE, 0);
+ gtk_widget_show (label);
+ }
gtk_box_pack_start (box, entry, TRUE, TRUE, 0);
+ gtk_widget_show (entry);
- fields->use_separator = TRUE;
+ return new_index;
}
-static GtkEntry *ygtk_field_entry_get_field (YGtkFieldEntry *fields, guint nb)
+void ygtk_field_entry_setup_field (YGtkFieldEntry *fields, guint index,
+ gint max_length, const gchar *valid_chars)
{
- GtkEntry *entry;
- GList *children = gtk_container_get_children (GTK_CONTAINER (fields));
- entry = g_list_nth_data (children, nb * 2);
- g_list_free (children);
- return entry;
+ GtkEntry *entry = ygtk_field_entry_get_field_widget (fields, index);
+ gtk_entry_set_max_length (entry, max_length == -1 ? 0 : max_length);
+ gtk_entry_set_width_chars (entry, max_length);
+ ygutils_setFilter (entry, valid_chars);
}
-void ygtk_field_entry_set_field_text (YGtkFieldEntry *fields, guint nb, const gchar *text)
+void ygtk_field_entry_set_field_text (YGtkFieldEntry *fields, guint index, const gchar *text)
{
- GtkEntry *entry = ygtk_field_entry_get_field (fields, nb);
+ GtkEntry *entry = ygtk_field_entry_get_field_widget (fields, index);
+
g_signal_handlers_block_by_func (entry,
(gpointer) ygtk_field_entry_entry_changed, fields);
g_signal_handlers_block_by_func (entry,
@@ -135,9 +158,9 @@
(gpointer) ygtk_field_entry_insert_text, fields);
}
-const gchar *ygtk_field_entry_get_field_text (YGtkFieldEntry *fields, guint nb)
+const gchar *ygtk_field_entry_get_field_text (YGtkFieldEntry *fields, guint index)
{
- GtkEntry *entry = ygtk_field_entry_get_field (fields, nb);
+ GtkEntry *entry = ygtk_field_entry_get_field_widget (fields, index);
return gtk_entry_get_text (entry);
}
Modified: trunk/gtk/unstable-libyui/src/ygtkfieldentry.h
URL: http://svn.opensuse.org/viewcvs/yast/trunk/gtk/unstable-libyui/src/ygtkfiel…
==============================================================================
--- trunk/gtk/unstable-libyui/src/ygtkfieldentry.h (original)
+++ trunk/gtk/unstable-libyui/src/ygtkfieldentry.h Thu Dec 6 13:42:24 2007
@@ -13,6 +13,7 @@
#define YGTK_FIELD_ENTRY_H
#include <gtk/gtkhbox.h>
+#include <gtk/gtkentry.h>
G_BEGIN_DECLS
#define YGTK_TYPE_FIELD_ENTRY (ygtk_field_entry_get_type ())
@@ -30,10 +31,6 @@
typedef struct _YGtkFieldEntry
{
GtkHBox parent;
-
- // private:
- // used to disable separator for the first field
- gboolean use_separator;
} YGtkFieldEntry;
typedef struct _YGtkFieldEntryClass
@@ -46,14 +43,16 @@
GtkWidget* ygtk_field_entry_new (void);
GType ygtk_field_entry_get_type (void) G_GNUC_CONST;
-// if this is the first field, separator will be ignored. max_length can be 0 to
-// disable it. valids_chars can be NULL to disable it.
-void ygtk_field_entry_add_field (YGtkFieldEntry *entry, gchar separator,
- guint max_length, const gchar *valid_chars);
-
-// convinience
-void ygtk_field_entry_set_field_text (YGtkFieldEntry *entry, guint nb, const gchar *text);
-const gchar *ygtk_field_entry_get_field_text (YGtkFieldEntry *entry, guint nb);
+// if this is the first field, separator will be ignored.
+guint ygtk_field_entry_add_field (YGtkFieldEntry *entry, gchar separator);
+//max_length can be 0 to disable it. valids_chars can be NULL to disable it.
+void ygtk_field_entry_setup_field (YGtkFieldEntry *entry, guint index,
+ gint max_length, const gchar *valid_chars);
+
+void ygtk_field_entry_set_field_text (YGtkFieldEntry *entry, guint index, const gchar *text);
+const gchar *ygtk_field_entry_get_field_text (YGtkFieldEntry *entry, guint index);
+
+GtkEntry *ygtk_field_entry_get_field_widget (YGtkFieldEntry *entry, guint index);
G_END_DECLS
#endif /*YGTK_FIELD_ENTRY_H*/
Modified: trunk/gtk/unstable-libyui/src/ygtkrichtext.c
URL: http://svn.opensuse.org/viewcvs/yast/trunk/gtk/unstable-libyui/src/ygtkrich…
==============================================================================
--- trunk/gtk/unstable-libyui/src/ygtkrichtext.c (original)
+++ trunk/gtk/unstable-libyui/src/ygtkrichtext.c Thu Dec 6 13:42:24 2007
@@ -539,28 +539,36 @@
}
/* String preparation methods. */
-
-#define IS_WHITE(c) (g_ascii_isspace (c) || (c) == '\t')
-
static char *elide_whitespace (const char *instr, int len)
{
GString *dest = g_string_new ("");
if (len < 0)
len = strlen (instr);
gboolean last_white = FALSE;
+ // transform breaklines in whitespace if in the middle of the text
+ gboolean special_white = FALSE, start_text = TRUE;
int i;
-// FIXME: whitespace elision needs to happen across tags [urk]
-// FIXME: perhaps post-process non-pre sections when they are complete ?
for (i = 0; i < len; i++)
{
char ch = instr[i];
- if (ch == '\r' || ch == '\n')
+ if (ch == '\n') {
+ if (!start_text)
+ special_white = TRUE;
continue;
+ }
if (ch == '\t')
ch = ' ';
- gboolean cur_white = IS_WHITE (ch);
+ gboolean cur_white = ch == ' ';
+ if (!cur_white) {
+ start_text = FALSE;
+ if (special_white) {
+ g_string_append_c (dest, ' ');
+ special_white = FALSE;
+ }
+ }
if (!cur_white || !last_white)
g_string_append_c (dest, ch);
+
last_white = cur_white;
}
Modified: trunk/gtk/unstable-libyui/src/ygtkwizard.c
URL: http://svn.opensuse.org/viewcvs/yast/trunk/gtk/unstable-libyui/src/ygtkwiza…
==============================================================================
--- trunk/gtk/unstable-libyui/src/ygtkwizard.c (original)
+++ trunk/gtk/unstable-libyui/src/ygtkwizard.c Thu Dec 6 13:42:24 2007
@@ -265,8 +265,13 @@
static void button_clicked_cb (GtkButton *button, YGtkWizard *wizard)
{
- gpointer id = g_object_get_data (G_OBJECT (button), "id");
- g_signal_emit (wizard, action_triggered_signal, 0, id, G_TYPE_POINTER);
+ gpointer id;
+ id = g_object_get_data (G_OBJECT (button), "ptr-id");
+ if (id)
+ g_signal_emit (wizard, action_triggered_signal, 0, id, G_TYPE_POINTER);
+ id = g_object_get_data (G_OBJECT (button), "str-id");
+ if (id)
+ g_signal_emit (wizard, action_triggered_signal, 0, id, G_TYPE_STRING);
}
static GtkWidget *button_new (YGtkWizard *wizard)
@@ -645,31 +650,53 @@
ygutils_setStockIcon (wizard->m_next_button, text);
}
-void ygtk_wizard_set_back_button_id (YGtkWizard *wizard, gpointer id,
- GDestroyNotify destroy_cb)
+void ygtk_wizard_set_back_button_ptr_id (YGtkWizard *wizard, gpointer id)
+{
+ g_object_set_data (G_OBJECT (wizard->m_back_button), "ptr-id", id);
+}
+
+void ygtk_wizard_set_next_button_ptr_id (YGtkWizard *wizard, gpointer id)
+{
+ g_object_set_data (G_OBJECT (wizard->m_next_button), "ptr-id", id);
+}
+
+void ygtk_wizard_set_abort_button_ptr_id (YGtkWizard *wizard, gpointer id)
+{
+ g_object_set_data (G_OBJECT (wizard->m_abort_button), "ptr-id", id);
+}
+
+void ygtk_wizard_set_release_notes_button_ptr_id (YGtkWizard *wizard, gpointer id)
+{
+ g_object_set_data (G_OBJECT (wizard->m_release_notes_button), "ptr-id", id);
+}
+
+void ygtk_wizard_set_back_button_str_id (YGtkWizard *wizard, const char *id)
+{
+ g_object_set_data_full (G_OBJECT (wizard->m_back_button), "str-id",
+ g_strdup (id), g_free);
+}
+
+void ygtk_wizard_set_next_button_str_id (YGtkWizard *wizard, const char *id)
{
- g_object_set_data_full (G_OBJECT (wizard->m_back_button), "id", id, destroy_cb);
+ g_object_set_data_full (G_OBJECT (wizard->m_next_button), "str-id",
+ g_strdup (id), g_free);
}
-void ygtk_wizard_set_next_button_id (YGtkWizard *wizard, gpointer id,
- GDestroyNotify destroy_cb)
+void ygtk_wizard_set_abort_button_str_id (YGtkWizard *wizard, const char *id)
{
- g_object_set_data_full (G_OBJECT (wizard->m_next_button), "id", id, destroy_cb);
+ g_object_set_data_full (G_OBJECT (wizard->m_abort_button), "str-id",
+ g_strdup (id), g_free);
}
-void ygtk_wizard_set_abort_button_id (YGtkWizard *wizard, gpointer id,
- GDestroyNotify destroy_cb)
+void ygtk_wizard_set_release_notes_button_str_id (YGtkWizard *wizard, const char *id)
{
- g_object_set_data_full (G_OBJECT (wizard->m_abort_button), "id", id, destroy_cb);
+ g_object_set_data_full (G_OBJECT (wizard->m_release_notes_button), "str-id",
+ g_strdup (id), g_free);
}
-void ygtk_wizard_set_release_notes_button_label (YGtkWizard *wizard,
- const gchar *text, gpointer id,
- GDestroyNotify destroy_cb)
+void ygtk_wizard_set_release_notes_button_label (YGtkWizard *wizard, const gchar *text)
{
gtk_button_set_label (GTK_BUTTON (wizard->m_release_notes_button), text);
- g_object_set_data_full (G_OBJECT (wizard->m_release_notes_button), "id",
- id, destroy_cb);
gtk_widget_show (wizard->m_release_notes_button);
}
Modified: trunk/gtk/unstable-libyui/src/ygtkwizard.h
URL: http://svn.opensuse.org/viewcvs/yast/trunk/gtk/unstable-libyui/src/ygtkwiza…
==============================================================================
--- trunk/gtk/unstable-libyui/src/ygtkwizard.h (original)
+++ trunk/gtk/unstable-libyui/src/ygtkwizard.h Thu Dec 6 13:42:24 2007
@@ -129,12 +129,14 @@
void ygtk_wizard_set_back_button_label (YGtkWizard *wizard, const char *text);
void ygtk_wizard_set_abort_button_label (YGtkWizard *wizard, const char *text);
void ygtk_wizard_set_next_button_label (YGtkWizard *wizard, const char *text);
-void ygtk_wizard_set_back_button_id (YGtkWizard *wizard, gpointer id,
- GDestroyNotify destroy_cb);
-void ygtk_wizard_set_next_button_id (YGtkWizard *wizard, gpointer id,
- GDestroyNotify destroy_cb);
-void ygtk_wizard_set_abort_button_id (YGtkWizard *wizard, gpointer id,
- GDestroyNotify destroy_cb);
+void ygtk_wizard_set_back_button_str_id (YGtkWizard *wizard, const char *id);
+void ygtk_wizard_set_next_button_str_id (YGtkWizard *wizard, const char *id);
+void ygtk_wizard_set_abort_button_str_id (YGtkWizard *wizard, const char *id);
+void ygtk_wizard_set_release_notes_button_str_id (YGtkWizard *wizard, const char *id);
+void ygtk_wizard_set_back_button_ptr_id (YGtkWizard *wizard, gpointer id);
+void ygtk_wizard_set_next_button_ptr_id (YGtkWizard *wizard, gpointer id);
+void ygtk_wizard_set_abort_button_ptr_id (YGtkWizard *wizard, gpointer id);
+void ygtk_wizard_set_release_notes_button_ptr_id (YGtkWizard *wizard, gpointer id);
void ygtk_wizard_enable_back_button (YGtkWizard *wizard, gboolean enable);
void ygtk_wizard_enable_next_button (YGtkWizard *wizard, gboolean enable);
void ygtk_wizard_enable_abort_button (YGtkWizard *wizard, gboolean enable);
@@ -163,9 +165,7 @@
gboolean ygtk_wizard_select_tree_item (YGtkWizard *wizard, const char *id);
const gchar *ygtk_wizard_get_tree_selection (YGtkWizard *wizard);
-void ygtk_wizard_set_release_notes_button_label (YGtkWizard *wizard,
- const gchar *text, gpointer id,
- GDestroyNotify destroy_cb);
+void ygtk_wizard_set_release_notes_button_label (YGtkWizard *wizard, const gchar *text);
void ygtk_wizard_show_release_notes_button (YGtkWizard *wizard, gboolean enable);
// You should call this method rather than GtkWidget's if you want
--
To unsubscribe, e-mail: yast-commit+unsubscribe(a)opensuse.org
For additional commands, e-mail: yast-commit+help(a)opensuse.org
1
0

[yast-commit] r42755 - /branches/tmp/coolo/qt4-port/src/YQMainWinDock.cc
by dmacvicar@svn.opensuse.org 06 Dec '07
by dmacvicar@svn.opensuse.org 06 Dec '07
06 Dec '07
Author: dmacvicar
Date: Thu Dec 6 12:55:41 2007
New Revision: 42755
URL: http://svn.opensuse.org/viewcvs/yast?rev=42755&view=rev
Log:
port to qt4
Modified:
branches/tmp/coolo/qt4-port/src/YQMainWinDock.cc
Modified: branches/tmp/coolo/qt4-port/src/YQMainWinDock.cc
URL: http://svn.opensuse.org/viewcvs/yast/branches/tmp/coolo/qt4-port/src/YQMain…
==============================================================================
--- branches/tmp/coolo/qt4-port/src/YQMainWinDock.cc (original)
+++ branches/tmp/coolo/qt4-port/src/YQMainWinDock.cc Thu Dec 6 12:55:41 2007
@@ -19,8 +19,8 @@
#define y2log_component "qt-ui"
#include <ycp/y2log.h>
-#include <qtimer.h>
-
+#include <QTimer>
+#include <QResizeEvent>
#include <YDialog.h>
#include <YQUI.h>
#include <YEvent.h>
@@ -41,14 +41,14 @@
YQMainWinDock::YQMainWinDock()
- : QWidget( 0, 0, // parent, name
+ : QWidget( 0, // parent, name
YQUI::ui()->noBorder() ?
- Qt::WStyle_Customize | Qt::WStyle_NoBorder :
- Qt::WType_TopLevel )
+ Qt::Widget :
+ Qt::Window )
{
- setCaption( "YaST2" );
+ setWindowTitle( "YaST2" );
- setFocusPolicy( QWidget::StrongFocus );
+ setFocusPolicy( Qt::StrongFocus );
resize( YQUI::ui()->defaultSize( YD_HORIZ ),
YQUI::ui()->defaultSize( YD_VERT ) );
@@ -71,7 +71,7 @@
{
QWidget * widget = dynamic_cast<QWidget *> ( event->child() );
- if ( widget && event->inserted() )
+ if ( widget && ( event->type() == QEvent::ChildAdded ) )
{
add( widget );
}
@@ -118,7 +118,7 @@
QWidget * dialog = _widgetStack.back();
dialog->raise();
- if ( ! dialog->isShown() )
+ if ( dialog->isHidden() )
dialog->show();
}
}
@@ -129,14 +129,14 @@
{
YUI_CHECK_PTR( dialog );
- if ( ! dialog->isShown() )
+ if ( dialog->isHidden() )
dialog->show();
y2debug( "Adding dialog %p to mainWinDock", dialog );
_widgetStack.push_back( dialog );
resizeVisibleChild();
- if ( ! isShown() )
+ if ( isHidden() )
show();
}
--
To unsubscribe, e-mail: yast-commit+unsubscribe(a)opensuse.org
For additional commands, e-mail: yast-commit+help(a)opensuse.org
1
0

[yast-commit] r42754 - /branches/tmp/coolo/qt4-port/src/pkg/
by dmacvicar@svn.opensuse.org 06 Dec '07
by dmacvicar@svn.opensuse.org 06 Dec '07
06 Dec '07
Author: dmacvicar
Date: Thu Dec 6 12:55:39 2007
New Revision: 42754
URL: http://svn.opensuse.org/viewcvs/yast?rev=42754&view=rev
Log:
more porting and make files use qt3support one by one
Modified:
branches/tmp/coolo/qt4-port/src/pkg/CMakeLists.txt
branches/tmp/coolo/qt4-port/src/pkg/YQPackageSelector.cc
branches/tmp/coolo/qt4-port/src/pkg/YQPackageSelectorBase.cc
branches/tmp/coolo/qt4-port/src/pkg/YQPatternSelector.cc
branches/tmp/coolo/qt4-port/src/pkg/YQPkgChangesDialog.cc
branches/tmp/coolo/qt4-port/src/pkg/YQPkgConflictDialog.cc
branches/tmp/coolo/qt4-port/src/pkg/YQPkgConflictList.cc
branches/tmp/coolo/qt4-port/src/pkg/YQPkgConflictList.h
branches/tmp/coolo/qt4-port/src/pkg/YQPkgDescriptionDialog.cc
branches/tmp/coolo/qt4-port/src/pkg/YQPkgDescriptionView.cc
branches/tmp/coolo/qt4-port/src/pkg/YQPkgDiskUsageList.cc
branches/tmp/coolo/qt4-port/src/pkg/YQPkgDiskUsageWarningDialog.cc
branches/tmp/coolo/qt4-port/src/pkg/YQPkgGenericDetailsView.cc
branches/tmp/coolo/qt4-port/src/pkg/YQPkgLangList.cc
branches/tmp/coolo/qt4-port/src/pkg/YQPkgList.cc
branches/tmp/coolo/qt4-port/src/pkg/YQPkgList.h
branches/tmp/coolo/qt4-port/src/pkg/YQPkgObjList.cc
branches/tmp/coolo/qt4-port/src/pkg/YQPkgObjList.h
branches/tmp/coolo/qt4-port/src/pkg/YQPkgPatchFilterView.cc
branches/tmp/coolo/qt4-port/src/pkg/YQPkgPatchList.cc
branches/tmp/coolo/qt4-port/src/pkg/YQPkgPatternList.cc
branches/tmp/coolo/qt4-port/src/pkg/YQPkgProductDialog.cc
branches/tmp/coolo/qt4-port/src/pkg/YQPkgRepoList.cc
branches/tmp/coolo/qt4-port/src/pkg/YQPkgRpmGroupTagsFilterView.cc
branches/tmp/coolo/qt4-port/src/pkg/YQPkgRpmGroupTagsFilterView.h
branches/tmp/coolo/qt4-port/src/pkg/YQPkgSearchFilterView.cc
branches/tmp/coolo/qt4-port/src/pkg/YQPkgSelDescriptionView.cc
branches/tmp/coolo/qt4-port/src/pkg/YQPkgSelList.cc
branches/tmp/coolo/qt4-port/src/pkg/YQPkgTechnicalDetailsView.cc
branches/tmp/coolo/qt4-port/src/pkg/YQPkgTextDialog.cc
branches/tmp/coolo/qt4-port/src/pkg/YQPkgVersionsView.cc
branches/tmp/coolo/qt4-port/src/pkg/YQSimplePatchSelector.cc
Modified: branches/tmp/coolo/qt4-port/src/pkg/CMakeLists.txt
URL: http://svn.opensuse.org/viewcvs/yast/branches/tmp/coolo/qt4-port/src/pkg/CM…
==============================================================================
--- branches/tmp/coolo/qt4-port/src/pkg/CMakeLists.txt (original)
+++ branches/tmp/coolo/qt4-port/src/pkg/CMakeLists.txt Thu Dec 6 12:55:39 2007
@@ -8,7 +8,7 @@
ADD_DEFINITIONS(
-DY2LOG=\\\"QT4\\\" ${QT_DEFINITIONS}
--DQT3_SUPPORT
+#-DQT3_SUPPORT
-DICONDIR=\\"${Y2QT_ICONDIR}\\"
-DLOCALEDIR=\\\"${Y2QT_LOCALEDIR}\\\"
-DTHEMEDIR=\\\"${Y2QT_THEMEDIR}\\\"
Modified: branches/tmp/coolo/qt4-port/src/pkg/YQPackageSelector.cc
URL: http://svn.opensuse.org/viewcvs/yast/branches/tmp/coolo/qt4-port/src/pkg/YQ…
==============================================================================
--- branches/tmp/coolo/qt4-port/src/pkg/YQPackageSelector.cc (original)
+++ branches/tmp/coolo/qt4-port/src/pkg/YQPackageSelector.cc Thu Dec 6 12:55:39 2007
@@ -19,6 +19,8 @@
/-*/
+#define QT3_SUPPORT 1
+
#define CHECK_DEPENDENCIES_ON_STARTUP 1
#define DEPENDENCY_FEEDBACK_IF_OK 1
#define AUTO_CHECK_DEPENDENCIES_DEFAULT true
@@ -488,7 +490,7 @@
_detailsViews->addTab( _pkgDescriptionView, _( "D&escription" ) );
_detailsViews->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding ) ); // hor/vert
- connect( _pkgList, SIGNAL( selectionChanged ( ZyppSel ) ),
+ connect( _pkgList, SIGNAL( currentItemChanged ( ZyppSel ) ),
_pkgDescriptionView, SLOT ( showDetailsIfVisible( ZyppSel ) ) );
//
@@ -500,7 +502,7 @@
_detailsViews->addTab( _pkgTechnicalDetailsView, _( "&Technical Data" ) );
- connect( _pkgList, SIGNAL( selectionChanged ( ZyppSel ) ),
+ connect( _pkgList, SIGNAL( currentItemChanged ( ZyppSel ) ),
_pkgTechnicalDetailsView, SLOT ( showDetailsIfVisible( ZyppSel ) ) );
@@ -514,7 +516,7 @@
_detailsViews->addTab( _pkgDependenciesView, _( "Dependencies" ) );
_detailsViews->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding ) ); // hor/vert
- connect( _pkgList, SIGNAL( selectionChanged ( ZyppSel ) ),
+ connect( _pkgList, SIGNAL( currentItemChanged ( ZyppSel ) ),
_pkgDependenciesView, SLOT ( showDetailsIfVisible( ZyppSel ) ) );
@@ -529,7 +531,7 @@
_detailsViews->addTab( _pkgVersionsView, _( "&Versions" ) );
- connect( _pkgList, SIGNAL( selectionChanged ( ZyppSel ) ),
+ connect( _pkgList, SIGNAL( currentItemChanged ( ZyppSel ) ),
_pkgVersionsView, SLOT ( showDetailsIfVisible( ZyppSel ) ) );
@@ -545,7 +547,7 @@
_detailsViews->addTab( _pkgFileListView, _( "File List" ) );
_detailsViews->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding ) ); // hor/vert
- connect( _pkgList, SIGNAL( selectionChanged ( ZyppSel ) ),
+ connect( _pkgList, SIGNAL( currentItemChanged ( ZyppSel ) ),
_pkgFileListView, SLOT ( showDetailsIfVisible( ZyppSel ) ) );
}
@@ -562,7 +564,7 @@
_detailsViews->addTab( _pkgChangeLogView, _( "Change Log" ) );
_detailsViews->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding ) ); // hor/vert
- connect( _pkgList, SIGNAL( selectionChanged ( ZyppSel ) ),
+ connect( _pkgList, SIGNAL( currentItemChanged ( ZyppSel ) ),
_pkgChangeLogView, SLOT ( showDetailsIfVisible( ZyppSel ) ) );
}
}
@@ -1131,7 +1133,7 @@
// The export might have left over a partially written file.
// Try to delete it. Don't care if it doesn't exist and unlink() fails.
- (void) unlink( (const char *) filename );
+ QFile::remove(filename);
// Post error popup
QMessageBox::warning( this, // parent
@@ -1154,7 +1156,7 @@
if ( ! filename.isEmpty() )
{
- y2milestone( "Importing package list from %s", (const char *) filename );
+ y2milestone( "Importing package list from %s", qPrintable(filename) );
try
{
@@ -1184,7 +1186,7 @@
y2debug( "Found %zu packages and %zu patterns in %s",
importPkg.size(),
importPatterns.size(),
- (const char *) filename );
+ qPrintable(filename) );
//
@@ -1225,7 +1227,7 @@
}
catch ( const zypp::Exception & exception )
{
- y2warning( "Error reading package list from %s", (const char *) filename );
+ y2warning( "Error reading package list from %s", qPrintable(filename) );
// Post error popup
QMessageBox::warning( this, // parent
@@ -1378,18 +1380,19 @@
void
YQPackageSelector::pkgExcludeRulesChanged( int menuItemID )
{
- if ( _viewMenu && _pkgList )
- {
- _viewMenu->setItemChecked( menuItemID, ! _viewMenu->isItemChecked( menuItemID ) );
-
- if ( _excludeDevelPkgs )
- _excludeDevelPkgs->enable( ! _viewMenu->isItemChecked( _viewShowDevelID ) );
-
- if ( _excludeDebugInfoPkgs )
- _excludeDebugInfoPkgs->enable( ! _viewMenu->isItemChecked( _viewShowDebugInfoID ) );
-
- _pkgList->applyExcludeRules();
- }
+//FIXME
+// if ( _viewMenu && _pkgList )
+// {
+// _viewMenu->setItemChecked( menuItemID, ! _viewMenu->isItemChecked( menuItemID ) );
+//
+// if ( _excludeDevelPkgs )
+// _excludeDevelPkgs->enable( ! _viewMenu->isItemChecked( _viewShowDevelID ) );
+//
+// if ( _excludeDebugInfoPkgs )
+// _excludeDebugInfoPkgs->enable( ! _viewMenu->isItemChecked( _viewShowDebugInfoID ) );
+//
+// _pkgList->applyExcludeRules();
+// }
}
@@ -1410,7 +1413,7 @@
{
subPkgs[ name ] = *it;
- y2debug( "Found subpackage: %s", (const char *) name );
+ y2debug( "Found subpackage: %s", qPrintable(name) );
}
}
@@ -1436,7 +1439,7 @@
case S_Taboo:
case S_Del:
// Don't install the subpackage
- y2milestone( "Ignoring unwanted subpackage %s", (const char *) subPkgName );
+ y2milestone( "Ignoring unwanted subpackage %s", qPrintable(subPkgName) );
break;
case S_AutoInstall:
@@ -1448,7 +1451,7 @@
if ( ! subPkg->installedObj() )
{
subPkg->set_status( S_Install );
- y2milestone( "Installing subpackage %s", (const char *) subPkgName );
+ y2milestone( "Installing subpackage %s", qPrintable(subPkgName) );
}
break;
@@ -1461,12 +1464,12 @@
if ( ! subPkg->installedObj() )
{
subPkg->set_status( S_Install );
- y2milestone( "Installing subpackage %s", (const char *) subPkgName );
+ y2milestone( "Installing subpackage %s", qPrintable(subPkgName) );
}
else
{
subPkg->set_status( S_Update );
- y2milestone( "Updating subpackage %s", (const char *) subPkgName );
+ y2milestone( "Updating subpackage %s", qPrintable(subPkgName) );
}
break;
Modified: branches/tmp/coolo/qt4-port/src/pkg/YQPackageSelectorBase.cc
URL: http://svn.opensuse.org/viewcvs/yast/branches/tmp/coolo/qt4-port/src/pkg/YQ…
==============================================================================
--- branches/tmp/coolo/qt4-port/src/pkg/YQPackageSelectorBase.cc (original)
+++ branches/tmp/coolo/qt4-port/src/pkg/YQPackageSelectorBase.cc Thu Dec 6 12:55:39 2007
@@ -374,9 +374,9 @@
{
if ( event )
{
- unsigned special_combo = ( Qt::ControlButton | Qt::ShiftButton | Qt::AltButton );
+ unsigned special_combo = ( Qt::ControlModifier | Qt::ShiftModifier | Qt::AltModifier );
- if ( ( event->state() & special_combo ) == special_combo )
+ if ( ( event->modifiers() & special_combo ) == special_combo )
{
if ( event->key() == Qt::Key_A )
{
Modified: branches/tmp/coolo/qt4-port/src/pkg/YQPatternSelector.cc
URL: http://svn.opensuse.org/viewcvs/yast/branches/tmp/coolo/qt4-port/src/pkg/YQ…
==============================================================================
--- branches/tmp/coolo/qt4-port/src/pkg/YQPatternSelector.cc (original)
+++ branches/tmp/coolo/qt4-port/src/pkg/YQPatternSelector.cc Thu Dec 6 12:55:39 2007
@@ -19,6 +19,8 @@
/-*/
+#define QT3_SUPPORT 1
+
#include <qapplication.h>
#include <q3hbox.h>
#include <q3header.h>
@@ -286,7 +288,7 @@
if ( _descriptionView )
{
- connect( _patternList, SIGNAL( selectionChanged( ZyppSel ) ),
+ connect( _patternList, SIGNAL( currentItemChanged( ZyppSel ) ),
_descriptionView, SLOT ( showDetails ( ZyppSel ) ) );
}
@@ -314,7 +316,7 @@
if ( _descriptionView )
{
- connect( _selList, SIGNAL( selectionChanged( ZyppSel ) ),
+ connect( _selList, SIGNAL( currentItemChanged( ZyppSel ) ),
_descriptionView, SLOT ( showDetails ( ZyppSel ) ) );
}
Modified: branches/tmp/coolo/qt4-port/src/pkg/YQPkgChangesDialog.cc
URL: http://svn.opensuse.org/viewcvs/yast/branches/tmp/coolo/qt4-port/src/pkg/YQ…
==============================================================================
--- branches/tmp/coolo/qt4-port/src/pkg/YQPkgChangesDialog.cc (original)
+++ branches/tmp/coolo/qt4-port/src/pkg/YQPkgChangesDialog.cc Thu Dec 6 12:55:39 2007
@@ -18,6 +18,7 @@
/-*/
+#define QT3_SUPPORT 1
#define y2log_component "qt-pkg"
#include <ycp/y2log.h>
Modified: branches/tmp/coolo/qt4-port/src/pkg/YQPkgConflictDialog.cc
URL: http://svn.opensuse.org/viewcvs/yast/branches/tmp/coolo/qt4-port/src/pkg/YQ…
==============================================================================
--- branches/tmp/coolo/qt4-port/src/pkg/YQPkgConflictDialog.cc (original)
+++ branches/tmp/coolo/qt4-port/src/pkg/YQPkgConflictDialog.cc Thu Dec 6 12:55:39 2007
@@ -18,6 +18,7 @@
/-*/
+#define QT3_SUPPORT 1
#define y2log_component "qt-pkg"
#include <ycp/y2log.h>
Modified: branches/tmp/coolo/qt4-port/src/pkg/YQPkgConflictList.cc
URL: http://svn.opensuse.org/viewcvs/yast/branches/tmp/coolo/qt4-port/src/pkg/YQ…
==============================================================================
--- branches/tmp/coolo/qt4-port/src/pkg/YQPkgConflictList.cc (original)
+++ branches/tmp/coolo/qt4-port/src/pkg/YQPkgConflictList.cc Thu Dec 6 12:55:39 2007
@@ -18,6 +18,7 @@
/-*/
+#define QT3_SUPPORT 1
#include <qpainter.h>
#include <qpixmap.h>
@@ -361,18 +362,18 @@
}
-void
-YQPkgConflict::paintCell( QPainter * painter,
- const QColorGroup & colorGroup,
- int column,
- int width,
- int alignment )
-{
- painter->setFont( YQUI::yqApp()->headingFont() );
-#if FIXME
- QY2ListViewItem::paintCell( painter, colorGroup, column, width, alignment );
-#endif
-}
+// void
+// YQPkgConflict::paintCell( QPainter * painter,
+// const QColorGroup & colorGroup,
+// int column,
+// int width,
+// int alignment )
+// {
+// painter->setFont( YQUI::yqApp()->headingFont() );
+// #if FIXME
+// QY2ListViewItem::paintCell( painter, colorGroup, column, width, alignment );
+// #endif
+// }
zypp::ProblemSolution_Ptr
Modified: branches/tmp/coolo/qt4-port/src/pkg/YQPkgConflictList.h
URL: http://svn.opensuse.org/viewcvs/yast/branches/tmp/coolo/qt4-port/src/pkg/YQ…
==============================================================================
--- branches/tmp/coolo/qt4-port/src/pkg/YQPkgConflictList.h (original)
+++ branches/tmp/coolo/qt4-port/src/pkg/YQPkgConflictList.h Thu Dec 6 12:55:39 2007
@@ -179,11 +179,11 @@
*
* Reimplemented from QY2ListViewItem.
**/
- virtual void paintCell( QPainter * painter,
- const QColorGroup & colorGroup,
- int column,
- int width,
- int alignment );
+// virtual void paintCell( QPainter * painter,
+// const QColorGroup & colorGroup,
+// int column,
+// int width,
+// int alignment );
// Data members
Modified: branches/tmp/coolo/qt4-port/src/pkg/YQPkgDescriptionDialog.cc
URL: http://svn.opensuse.org/viewcvs/yast/branches/tmp/coolo/qt4-port/src/pkg/YQ…
==============================================================================
--- branches/tmp/coolo/qt4-port/src/pkg/YQPkgDescriptionDialog.cc (original)
+++ branches/tmp/coolo/qt4-port/src/pkg/YQPkgDescriptionDialog.cc Thu Dec 6 12:55:39 2007
@@ -18,6 +18,7 @@
/-*/
+#define QT3_SUPPORT 1
#define y2log_component "qt-pkg"
#include <ycp/y2log.h>
@@ -82,7 +83,7 @@
Q_CHECK_PTR( _pkgDescription );
_pkgDescription->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding ) ); // hor/vert
- connect( _pkgList, SIGNAL( selectionChanged ( ZyppSel ) ),
+ connect( _pkgList, SIGNAL( currentItemChanged ( ZyppSel ) ),
_pkgDescription, SLOT ( showDetailsIfVisible( ZyppSel ) ) );
Modified: branches/tmp/coolo/qt4-port/src/pkg/YQPkgDescriptionView.cc
URL: http://svn.opensuse.org/viewcvs/yast/branches/tmp/coolo/qt4-port/src/pkg/YQ…
==============================================================================
--- branches/tmp/coolo/qt4-port/src/pkg/YQPkgDescriptionView.cc (original)
+++ branches/tmp/coolo/qt4-port/src/pkg/YQPkgDescriptionView.cc Thu Dec 6 12:55:39 2007
@@ -16,6 +16,8 @@
/-*/
+#define QT3_SUPPORT 1
+
#define y2log_component "qt-pkg"
#include <ycp/y2log.h>
Modified: branches/tmp/coolo/qt4-port/src/pkg/YQPkgDiskUsageList.cc
URL: http://svn.opensuse.org/viewcvs/yast/branches/tmp/coolo/qt4-port/src/pkg/YQ…
==============================================================================
--- branches/tmp/coolo/qt4-port/src/pkg/YQPkgDiskUsageList.cc (original)
+++ branches/tmp/coolo/qt4-port/src/pkg/YQPkgDiskUsageList.cc Thu Dec 6 12:55:39 2007
@@ -18,6 +18,8 @@
/-*/
+#define QT3_SUPPORT 1
+
#define y2log_component "qt-pkg"
#include <ycp/y2log.h>
Modified: branches/tmp/coolo/qt4-port/src/pkg/YQPkgDiskUsageWarningDialog.cc
URL: http://svn.opensuse.org/viewcvs/yast/branches/tmp/coolo/qt4-port/src/pkg/YQ…
==============================================================================
--- branches/tmp/coolo/qt4-port/src/pkg/YQPkgDiskUsageWarningDialog.cc (original)
+++ branches/tmp/coolo/qt4-port/src/pkg/YQPkgDiskUsageWarningDialog.cc Thu Dec 6 12:55:39 2007
@@ -18,6 +18,7 @@
/-*/
+#define QT3_SUPPORT 1
#define y2log_component "qt-pkg"
#include <ycp/y2log.h>
Modified: branches/tmp/coolo/qt4-port/src/pkg/YQPkgGenericDetailsView.cc
URL: http://svn.opensuse.org/viewcvs/yast/branches/tmp/coolo/qt4-port/src/pkg/YQ…
==============================================================================
--- branches/tmp/coolo/qt4-port/src/pkg/YQPkgGenericDetailsView.cc (original)
+++ branches/tmp/coolo/qt4-port/src/pkg/YQPkgGenericDetailsView.cc Thu Dec 6 12:55:39 2007
@@ -16,6 +16,8 @@
/-*/
+#define QT3_SUPPORT 1
+
#define y2log_component "qt-pkg"
#include <ycp/y2log.h>
#include <qtabwidget.h>
Modified: branches/tmp/coolo/qt4-port/src/pkg/YQPkgLangList.cc
URL: http://svn.opensuse.org/viewcvs/yast/branches/tmp/coolo/qt4-port/src/pkg/YQ…
==============================================================================
--- branches/tmp/coolo/qt4-port/src/pkg/YQPkgLangList.cc (original)
+++ branches/tmp/coolo/qt4-port/src/pkg/YQPkgLangList.cc Thu Dec 6 12:55:39 2007
@@ -48,7 +48,7 @@
setAllColumnsShowFocus( true );
#endif
- connect( this, SIGNAL( selectionChanged ( Q3ListViewItem * ) ),
+ connect( this, SIGNAL( currentItemChanged ( QTreeWidgetItem *, QTreeWidgetItem * ) ),
this, SLOT ( filter() ) );
fillList();
Modified: branches/tmp/coolo/qt4-port/src/pkg/YQPkgList.cc
URL: http://svn.opensuse.org/viewcvs/yast/branches/tmp/coolo/qt4-port/src/pkg/YQ…
==============================================================================
--- branches/tmp/coolo/qt4-port/src/pkg/YQPkgList.cc (original)
+++ branches/tmp/coolo/qt4-port/src/pkg/YQPkgList.cc Thu Dec 6 12:55:39 2007
@@ -18,6 +18,8 @@
/-*/
+#define QT3_SUPPORT 1
+
#define SOURCE_RPM_DISABLED 0
#define y2log_component "qt-pkg"
Modified: branches/tmp/coolo/qt4-port/src/pkg/YQPkgList.h
URL: http://svn.opensuse.org/viewcvs/yast/branches/tmp/coolo/qt4-port/src/pkg/YQ…
==============================================================================
--- branches/tmp/coolo/qt4-port/src/pkg/YQPkgList.h (original)
+++ branches/tmp/coolo/qt4-port/src/pkg/YQPkgList.h Thu Dec 6 12:55:39 2007
@@ -151,8 +151,8 @@
void setDontInstallListSourceRpms() { setInstallListSourceRpms( false ); }
- // No separate selectionChanged( ZyppPkg ) signal:
- // Use YQPkgObjList::selectionChanged( ZyppObj ) instead
+ // No separate currentItemChanged( ZyppPkg ) signal:
+ // Use YQPkgObjList::currentItemChanged( ZyppObj ) instead
// and dynamic_cast to ZyppPkg if required.
// This saves duplicating a lot of code.
Modified: branches/tmp/coolo/qt4-port/src/pkg/YQPkgObjList.cc
URL: http://svn.opensuse.org/viewcvs/yast/branches/tmp/coolo/qt4-port/src/pkg/YQ…
==============================================================================
--- branches/tmp/coolo/qt4-port/src/pkg/YQPkgObjList.cc (original)
+++ branches/tmp/coolo/qt4-port/src/pkg/YQPkgObjList.cc Thu Dec 6 12:55:39 2007
@@ -18,6 +18,8 @@
/-*/
+#define QT3_SUPPORT 1
+
#define y2log_component "qt-pkg"
#include <ycp/y2log.h>
#include <QPixmap>
@@ -73,8 +75,8 @@
connect( this, SIGNAL( columnDoubleClicked ( int, QTreeWidgetItem *, int, const QPoint & ) ),
this, SLOT ( pkgObjClicked ( int, QTreeWidgetItem *, int, const QPoint & ) ) );
- connect( this, SIGNAL( selectionChanged ( QTreeWidgetItem * ) ),
- this, SLOT ( selectionChangedInternal( QTreeWidgetItem * ) ) );
+ connect( this, SIGNAL( currentItemChanged ( QTreeWidgetItem *, QTreeWidgetItem * ) ),
+ this, SLOT ( currentItemChangedInternal( QTreeWidgetItem * ) ) );
}
@@ -158,18 +160,18 @@
void
-YQPkgObjList::selectionChangedInternal( QTreeWidgetItem * listViewItem )
+YQPkgObjList::currentItemChangedInternal( QTreeWidgetItem * listViewItem )
{
YQPkgObjListItem * item = dynamic_cast<YQPkgObjListItem *> (listViewItem);
- emit selectionChanged( item ? item->selectable() : ZyppSel() );
+ emit currentItemChanged( item ? item->selectable() : ZyppSel() );
}
void
YQPkgObjList::clear()
{
- emit selectionChanged( ZyppSel() );
+ emit currentItemChanged( ZyppSel() );
_excludedItems->clear();
QY2ListView::clear();
Modified: branches/tmp/coolo/qt4-port/src/pkg/YQPkgObjList.h
URL: http://svn.opensuse.org/viewcvs/yast/branches/tmp/coolo/qt4-port/src/pkg/YQ…
==============================================================================
--- branches/tmp/coolo/qt4-port/src/pkg/YQPkgObjList.h (original)
+++ branches/tmp/coolo/qt4-port/src/pkg/YQPkgObjList.h Thu Dec 6 12:55:39 2007
@@ -58,7 +58,7 @@
virtual ~YQPkgObjList();
// avoiding warning about virtuals
- using QTreeView::selectionChanged;
+ using QTreeWidget::currentItemChanged;
public:
@@ -184,7 +184,7 @@
/**
* Reimplemented from QY2ListView:
- * Emit selectionChanged() signal after clearing the list.
+ * Emit currentItemChanged() signal after clearing the list.
**/
virtual void clear();
@@ -248,7 +248,7 @@
/**
* Dispatcher slot for selection change - internal only.
**/
- virtual void selectionChangedInternal( QTreeWidgetItem * item );
+ virtual void currentItemChangedInternal( QTreeWidgetItem * item );
signals:
@@ -257,7 +257,7 @@
* Emitted when a zypp::ui::Selectable is selected.
* May be called with a null poiner if no zypp::ResObject is selected.
**/
- void selectionChanged( ZyppSel selectable );
+ void currentItemChanged( ZyppSel selectable );
/**
* Emitted when the status of a zypp::ResObject is changed.
Modified: branches/tmp/coolo/qt4-port/src/pkg/YQPkgPatchFilterView.cc
URL: http://svn.opensuse.org/viewcvs/yast/branches/tmp/coolo/qt4-port/src/pkg/YQ…
==============================================================================
--- branches/tmp/coolo/qt4-port/src/pkg/YQPkgPatchFilterView.cc (original)
+++ branches/tmp/coolo/qt4-port/src/pkg/YQPkgPatchFilterView.cc Thu Dec 6 12:55:39 2007
@@ -18,6 +18,7 @@
/-*/
+#define QT3_SUPPORT 1
#define y2log_component "qt-pkg"
#include <ycp/y2log.h>
@@ -114,7 +115,7 @@
#endif
- connect( _patchList, SIGNAL( selectionChanged ( ZyppSel ) ),
+ connect( _patchList, SIGNAL( currentItemChanged ( ZyppSel ) ),
_descriptionView, SLOT ( showDetailsIfVisible( ZyppSel ) ) );
connect( _patchList, SIGNAL( statusChanged() ),
Modified: branches/tmp/coolo/qt4-port/src/pkg/YQPkgPatchList.cc
URL: http://svn.opensuse.org/viewcvs/yast/branches/tmp/coolo/qt4-port/src/pkg/YQ…
==============================================================================
--- branches/tmp/coolo/qt4-port/src/pkg/YQPkgPatchList.cc (original)
+++ branches/tmp/coolo/qt4-port/src/pkg/YQPkgPatchList.cc Thu Dec 6 12:55:39 2007
@@ -18,6 +18,7 @@
/-*/
+#define QT3_SUPPORT 1
#define y2log_component "qt-pkg"
#include <ycp/y2log.h>
@@ -70,7 +71,7 @@
setAllColumnsShowFocus( true );
setColumnAlignment( sizeCol(), Qt::AlignRight );
- connect( this, SIGNAL( selectionChanged ( QTreeWidgetItem * ) ),
+ connect( this, SIGNAL( currentItemChanged ( QTreeWidgetItem * ) ),
this, SLOT ( filter() ) );
setSorting( categoryCol() );
@@ -92,9 +93,9 @@
{
// Delayed initialization after widget is fully created etc.
- // Only now send selectionChanged() signal so attached details views also
+ // Only now send currentItemChanged() signal so attached details views also
// display something if their showDetailsIfVisible() slot is connected to
- // selectionChanged() signals.
+ // currentItemChanged() signals.
selectSomething();
}
Modified: branches/tmp/coolo/qt4-port/src/pkg/YQPkgPatternList.cc
URL: http://svn.opensuse.org/viewcvs/yast/branches/tmp/coolo/qt4-port/src/pkg/YQ…
==============================================================================
--- branches/tmp/coolo/qt4-port/src/pkg/YQPkgPatternList.cc (original)
+++ branches/tmp/coolo/qt4-port/src/pkg/YQPkgPatternList.cc Thu Dec 6 12:55:39 2007
@@ -18,14 +18,15 @@
/-*/
+#define QT3_SUPPORT 1
#define y2log_component "qt-pkg"
#include <ycp/y2log.h>
-#include <qregexp.h>
+#include <QRegExp>
#include <zypp/ZYppFactory.h>
#include <zypp/Resolver.h>
-#include <qpainter.h>
-#include <q3header.h>
+#include <QPainter>
+#include <QHeaderView>
#include <zypp/ui/PatternContents.h>
#include "YQi18n.h"
@@ -46,7 +47,8 @@
int numCol = 0;
#if FIXME
- addColumn( "" ); _statusCol = numCol++;
+ QStringList headers;
+ headers << ""; _statusCol = numCol++;
// Translators: "Pattern" refers to so-called "installation patterns",
// i.e., specific task-oriented groups of packages, like "everything that
@@ -55,8 +57,9 @@
// configuring the web server. For the scope of the package selector, this
// is only of little relevance, though.
- addColumn( _( "Pattern" ) ); _summaryCol = numCol++;
+ headers << _( "Pattern" ); _summaryCol = numCol++;
+ setHeaderLabels(headers);
// Can use the same colum for "broken" and "satisfied":
// Both states are mutually exclusive
@@ -71,7 +74,7 @@
if ( autoFilter )
{
- connect( this, SIGNAL( selectionChanged( QTreeWidgetItem * ) ),
+ connect( this, SIGNAL( currentItemChanged( QTreeWidgetItem * ) ),
this, SLOT ( filter() ) );
}
@@ -208,6 +211,7 @@
else
item = new YQPkgPatternListItem( this, selectable, zyppPattern );
+ addTopLevelItem(item);
applyExcludeRules( item );
}
@@ -216,7 +220,7 @@
YQPkgPatternList::selection() const
{
#if FIXME
- QTreeWidgetItem * item = selectedItem();
+ QTreeWidgetItem * item = currentItem();
if ( ! item )
return 0;
@@ -244,7 +248,7 @@
{
if ( col == statusCol() )
{
- categoryItem->setOpen( ! categoryItem->isOpen() );
+ categoryItem->setOpen( ! categoryItem->isExpanded() );
}
}
}
Modified: branches/tmp/coolo/qt4-port/src/pkg/YQPkgProductDialog.cc
URL: http://svn.opensuse.org/viewcvs/yast/branches/tmp/coolo/qt4-port/src/pkg/YQ…
==============================================================================
--- branches/tmp/coolo/qt4-port/src/pkg/YQPkgProductDialog.cc (original)
+++ branches/tmp/coolo/qt4-port/src/pkg/YQPkgProductDialog.cc Thu Dec 6 12:55:39 2007
@@ -18,6 +18,7 @@
/-*/
+#define QT3_SUPPORT 1
#define y2log_component "qt-pkg"
#include <ycp/y2log.h>
@@ -94,7 +95,7 @@
_detailsViews->addTab( _dependenciesView, _( "Dependencies" ) );
_dependenciesView->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding ) ); // hor/vert
- connect( _productList, SIGNAL( selectionChanged ( ZyppSel ) ),
+ connect( _productList, SIGNAL( currentItemChanged ( ZyppSel ) ),
_dependenciesView, SLOT ( showDetailsIfVisible( ZyppSel ) ) );
@@ -127,7 +128,7 @@
{
// Delayed initialization after widget is fully created etc.
- // Only now send selectionChanged() signal so the details views display something
+ // Only now send currentItemChanged() signal so the details views display something
// (showDetailsIfVisible() shows only something if the widget is visible,
// as the method name implies)
_productList->selectSomething();
Modified: branches/tmp/coolo/qt4-port/src/pkg/YQPkgRepoList.cc
URL: http://svn.opensuse.org/viewcvs/yast/branches/tmp/coolo/qt4-port/src/pkg/YQ…
==============================================================================
--- branches/tmp/coolo/qt4-port/src/pkg/YQPkgRepoList.cc (original)
+++ branches/tmp/coolo/qt4-port/src/pkg/YQPkgRepoList.cc Thu Dec 6 12:55:39 2007
@@ -18,6 +18,7 @@
/-*/
+#define QT3_SUPPORT 1
#include <algorithm>
#include <qdatetime.h>
@@ -54,7 +55,7 @@
setAllColumnsShowFocus( true );
setSelectionMode( Q3ListView::Extended ); // allow multi-selection with Ctrl-mouse
- connect( this, SIGNAL( selectionChanged() ),
+ connect( this, SIGNAL( currentItemChanged() ),
this, SLOT ( filterIfVisible()) );
fillList();
Modified: branches/tmp/coolo/qt4-port/src/pkg/YQPkgRpmGroupTagsFilterView.cc
URL: http://svn.opensuse.org/viewcvs/yast/branches/tmp/coolo/qt4-port/src/pkg/YQ…
==============================================================================
--- branches/tmp/coolo/qt4-port/src/pkg/YQPkgRpmGroupTagsFilterView.cc (original)
+++ branches/tmp/coolo/qt4-port/src/pkg/YQPkgRpmGroupTagsFilterView.cc Thu Dec 6 12:55:39 2007
@@ -32,16 +32,16 @@
YQPkgRpmGroupTagsFilterView::YQPkgRpmGroupTagsFilterView( QWidget * parent )
- : Q3ListView( parent )
+ : QTreeWidget( parent )
{
- addColumn( _( "Package Groups" ) );
+ setHeaderLabels( QStringList(_( "Package Groups" )) );
setRootIsDecorated( true );
cloneTree( rpmGroupsTree()->root(), 0 );
new YQPkgRpmGroupTag( this, _( "zzz All" ), 0 );
- connect( this, SIGNAL( selectionChanged ( Q3ListViewItem * ) ),
- this, SLOT ( slotSelectionChanged ( Q3ListViewItem * ) ) );
+ connect( this, SIGNAL( currentItemChanged ( QTreeWidgetItem *, QTreeWidgetItem * ) ),
+ this, SLOT ( slotSelectionChanged ( QTreeWidgetItem * ) ) );
selectSomething();
}
@@ -101,8 +101,8 @@
clone = new YQPkgRpmGroupTag( this, child );
Q_CHECK_PTR( clone );
- clone->setOpen( clone->depth() < 1 );
-
+ //FIXME clone->setExpanded( clone->depth() < 1 );
+ clone->setExpanded( true );
cloneTree( child, clone );
child = child->next();
}
@@ -112,10 +112,11 @@
void
YQPkgRpmGroupTagsFilterView::selectSomething()
{
- Q3ListViewItem * item = firstChild();
-
- if ( item )
- setSelected( item, true );
+// FIXME
+// QTreeWidgetItem * item = children().first();
+//
+// if ( item )
+// setCurrentItem(item);
}
@@ -168,7 +169,7 @@
void
-YQPkgRpmGroupTagsFilterView::slotSelectionChanged( Q3ListViewItem * newSelection )
+YQPkgRpmGroupTagsFilterView::slotSelectionChanged( QTreeWidgetItem * newSelection )
{
YQPkgRpmGroupTag * sel = dynamic_cast<YQPkgRpmGroupTag *>( newSelection );
@@ -218,12 +219,12 @@
YQPkgRpmGroupTag *
YQPkgRpmGroupTagsFilterView::selection() const
{
- Q3ListViewItem * item = selectedItem();
+ QTreeWidgetItem * item = currentItem();
if ( ! item )
return 0;
- return dynamic_cast<YQPkgRpmGroupTag *> ( selectedItem() );
+ return dynamic_cast<YQPkgRpmGroupTag *> ( item );
}
@@ -233,7 +234,7 @@
YQPkgRpmGroupTag::YQPkgRpmGroupTag( YQPkgRpmGroupTagsFilterView * parentFilterView,
YStringTreeItem * rpmGroup )
- : Q3ListViewItem( parentFilterView )
+ : QTreeWidgetItem( parentFilterView )
, _filterView( parentFilterView )
, _rpmGroup( rpmGroup )
{
@@ -244,7 +245,7 @@
YQPkgRpmGroupTag::YQPkgRpmGroupTag( YQPkgRpmGroupTagsFilterView * parentFilterView,
YQPkgRpmGroupTag * parentGroupTag,
YStringTreeItem * rpmGroup )
- : Q3ListViewItem( parentGroupTag )
+ : QTreeWidgetItem( parentGroupTag )
, _filterView( parentFilterView )
, _rpmGroup( rpmGroup )
{
@@ -255,7 +256,7 @@
YQPkgRpmGroupTag::YQPkgRpmGroupTag( YQPkgRpmGroupTagsFilterView * parentFilterView,
const QString & rpmGroupName,
YStringTreeItem * rpmGroup )
- : Q3ListViewItem( parentFilterView )
+ : QTreeWidgetItem( parentFilterView )
, _filterView( parentFilterView )
, _rpmGroup( rpmGroup )
{
Modified: branches/tmp/coolo/qt4-port/src/pkg/YQPkgRpmGroupTagsFilterView.h
URL: http://svn.opensuse.org/viewcvs/yast/branches/tmp/coolo/qt4-port/src/pkg/YQ…
==============================================================================
--- branches/tmp/coolo/qt4-port/src/pkg/YQPkgRpmGroupTagsFilterView.h (original)
+++ branches/tmp/coolo/qt4-port/src/pkg/YQPkgRpmGroupTagsFilterView.h Thu Dec 6 12:55:39 2007
@@ -21,7 +21,7 @@
#define YQPkgRpmGroupTagsFilterView_h
#include "YQZypp.h"
-#include <q3listview.h>
+#include <QTreeWidget>
#include <YRpmGroupsTree.h>
@@ -35,7 +35,7 @@
* signals if any group tag is selected so a package list can be filled or
* updated.
**/
-class YQPkgRpmGroupTagsFilterView : public Q3ListView
+class YQPkgRpmGroupTagsFilterView : public QTreeWidget
{
Q_OBJECT
@@ -89,7 +89,7 @@
/**
* Select a list entry (if there is any).
* Usually this will be the first list entry, but don't rely on that - this
- * might change without notice. Emits signal selectionChanged().
+ * might change without notice. Emits signal currentItemChanged().
**/
void selectSomething();
@@ -125,7 +125,7 @@
/**
* Update _selectedRpmGroup and filter data
**/
- void slotSelectionChanged( Q3ListViewItem * newSelection );
+ void slotSelectionChanged( QTreeWidgetItem * newSelection );
protected:
@@ -155,7 +155,7 @@
-class YQPkgRpmGroupTag: public Q3ListViewItem
+class YQPkgRpmGroupTag: public QTreeWidgetItem
{
public:
Modified: branches/tmp/coolo/qt4-port/src/pkg/YQPkgSearchFilterView.cc
URL: http://svn.opensuse.org/viewcvs/yast/branches/tmp/coolo/qt4-port/src/pkg/YQ…
==============================================================================
--- branches/tmp/coolo/qt4-port/src/pkg/YQPkgSearchFilterView.cc (original)
+++ branches/tmp/coolo/qt4-port/src/pkg/YQPkgSearchFilterView.cc Thu Dec 6 12:55:39 2007
@@ -18,6 +18,8 @@
/-*/
+#define QT3_SUPPORT 1
+
#include <qcheckbox.h>
#include <qcombobox.h>
#include <qlabel.h>
Modified: branches/tmp/coolo/qt4-port/src/pkg/YQPkgSelDescriptionView.cc
URL: http://svn.opensuse.org/viewcvs/yast/branches/tmp/coolo/qt4-port/src/pkg/YQ…
==============================================================================
--- branches/tmp/coolo/qt4-port/src/pkg/YQPkgSelDescriptionView.cc (original)
+++ branches/tmp/coolo/qt4-port/src/pkg/YQPkgSelDescriptionView.cc Thu Dec 6 12:55:39 2007
@@ -16,6 +16,7 @@
/-*/
+#define QT3_SUPPORT 1
#define y2log_component "qt-pkg"
#include <ycp/y2log.h>
Modified: branches/tmp/coolo/qt4-port/src/pkg/YQPkgSelList.cc
URL: http://svn.opensuse.org/viewcvs/yast/branches/tmp/coolo/qt4-port/src/pkg/YQ…
==============================================================================
--- branches/tmp/coolo/qt4-port/src/pkg/YQPkgSelList.cc (original)
+++ branches/tmp/coolo/qt4-port/src/pkg/YQPkgSelList.cc Thu Dec 6 12:55:39 2007
@@ -48,7 +48,7 @@
if ( autoFilter )
{
- connect( this, SIGNAL( selectionChanged( QTreeWidgetItem * ) ),
+ connect( this, SIGNAL( currentItemChanged( QTreeWidgetItem * ) ),
this, SLOT ( filter() ) );
}
Modified: branches/tmp/coolo/qt4-port/src/pkg/YQPkgTechnicalDetailsView.cc
URL: http://svn.opensuse.org/viewcvs/yast/branches/tmp/coolo/qt4-port/src/pkg/YQ…
==============================================================================
--- branches/tmp/coolo/qt4-port/src/pkg/YQPkgTechnicalDetailsView.cc (original)
+++ branches/tmp/coolo/qt4-port/src/pkg/YQPkgTechnicalDetailsView.cc Thu Dec 6 12:55:39 2007
@@ -18,6 +18,8 @@
/-*/
+#define QT3_SUPPORT 1
+
#define y2log_component "qt-pkg"
#include <ycp/y2log.h>
Modified: branches/tmp/coolo/qt4-port/src/pkg/YQPkgTextDialog.cc
URL: http://svn.opensuse.org/viewcvs/yast/branches/tmp/coolo/qt4-port/src/pkg/YQ…
==============================================================================
--- branches/tmp/coolo/qt4-port/src/pkg/YQPkgTextDialog.cc (original)
+++ branches/tmp/coolo/qt4-port/src/pkg/YQPkgTextDialog.cc Thu Dec 6 12:55:39 2007
@@ -18,6 +18,7 @@
/-*/
+#define QT3_SUPPORT 1
#define y2log_component "qt-pkg"
#include <ycp/y2log.h>
Modified: branches/tmp/coolo/qt4-port/src/pkg/YQPkgVersionsView.cc
URL: http://svn.opensuse.org/viewcvs/yast/branches/tmp/coolo/qt4-port/src/pkg/YQ…
==============================================================================
--- branches/tmp/coolo/qt4-port/src/pkg/YQPkgVersionsView.cc (original)
+++ branches/tmp/coolo/qt4-port/src/pkg/YQPkgVersionsView.cc Thu Dec 6 12:55:39 2007
@@ -18,6 +18,8 @@
/-*/
+#define QT3_SUPPORT 1
+
#define y2log_component "qt-pkg"
#include <YQZypp.h>
@@ -75,7 +77,7 @@
this, SLOT ( reload (QWidget *) ) );
}
- connect( this, SIGNAL( selectionChanged () ),
+ connect( this, SIGNAL( currentItemChanged () ),
this, SLOT ( checkForChangedCandidate() ) );
}
Modified: branches/tmp/coolo/qt4-port/src/pkg/YQSimplePatchSelector.cc
URL: http://svn.opensuse.org/viewcvs/yast/branches/tmp/coolo/qt4-port/src/pkg/YQ…
==============================================================================
--- branches/tmp/coolo/qt4-port/src/pkg/YQSimplePatchSelector.cc (original)
+++ branches/tmp/coolo/qt4-port/src/pkg/YQSimplePatchSelector.cc Thu Dec 6 12:55:39 2007
@@ -18,6 +18,8 @@
/-*/
+#define QT3_SUPPORT 1
+
#include <qapplication.h>
#include <q3hbox.h>
#include <q3header.h>
--
To unsubscribe, e-mail: yast-commit+unsubscribe(a)opensuse.org
For additional commands, e-mail: yast-commit+help(a)opensuse.org
1
0

[yast-commit] r42753 - in /trunk/gtk/unstable/mockups/package-selector: selector-screenshot-changes.png selector-screenshot-patterns.png selector-screenshot.png
by visnov@svn.opensuse.org 06 Dec '07
by visnov@svn.opensuse.org 06 Dec '07
06 Dec '07
Author: visnov
Date: Thu Dec 6 12:44:35 2007
New Revision: 42753
URL: http://svn.opensuse.org/viewcvs/yast?rev=42753&view=rev
Log:
added screenshots of the new package selector
Added:
trunk/gtk/unstable/mockups/package-selector/selector-screenshot-changes.png (with props)
trunk/gtk/unstable/mockups/package-selector/selector-screenshot-patterns.png (with props)
trunk/gtk/unstable/mockups/package-selector/selector-screenshot.png (with props)
Added: trunk/gtk/unstable/mockups/package-selector/selector-screenshot-changes.png
URL: http://svn.opensuse.org/viewcvs/yast/trunk/gtk/unstable/mockups/package-sel…
==============================================================================
Binary file - no diff available.
Added: trunk/gtk/unstable/mockups/package-selector/selector-screenshot-patterns.png
URL: http://svn.opensuse.org/viewcvs/yast/trunk/gtk/unstable/mockups/package-sel…
==============================================================================
Binary file - no diff available.
Added: trunk/gtk/unstable/mockups/package-selector/selector-screenshot.png
URL: http://svn.opensuse.org/viewcvs/yast/trunk/gtk/unstable/mockups/package-sel…
==============================================================================
Binary file - no diff available.
--
To unsubscribe, e-mail: yast-commit+unsubscribe(a)opensuse.org
For additional commands, e-mail: yast-commit+help(a)opensuse.org
1
0

[yast-commit] r42752 - in /trunk/update: package/yast2-update.changes src/clients/update_proposal.ycp src/modules/RootPart.ycp
by locilka@svn.opensuse.org 06 Dec '07
by locilka@svn.opensuse.org 06 Dec '07
06 Dec '07
Author: locilka
Date: Thu Dec 6 10:03:40 2007
New Revision: 42752
URL: http://svn.opensuse.org/viewcvs/yast?rev=42752&view=rev
Log:
- Merged proofread texts.
Modified:
trunk/update/package/yast2-update.changes
trunk/update/src/clients/update_proposal.ycp
trunk/update/src/modules/RootPart.ycp
Modified: trunk/update/package/yast2-update.changes
URL: http://svn.opensuse.org/viewcvs/yast/trunk/update/package/yast2-update.chan…
==============================================================================
--- trunk/update/package/yast2-update.changes (original)
+++ trunk/update/package/yast2-update.changes Thu Dec 6 10:03:40 2007
@@ -1,4 +1,9 @@
-------------------------------------------------------------------
+Thu Dec 6 10:03:09 CET 2007 - locilka(a)suse.cz
+
+- Merged proofread texts.
+
+-------------------------------------------------------------------
Mon Nov 19 16:58:31 CET 2007 - locilka(a)suse.cz
- Unified used terminology (repositories) (FATE #302970).
Modified: trunk/update/src/clients/update_proposal.ycp
URL: http://svn.opensuse.org/viewcvs/yast/trunk/update/src/clients/update_propos…
==============================================================================
--- trunk/update/src/clients/update_proposal.ycp (original)
+++ trunk/update/src/clients/update_proposal.ycp Thu Dec 6 10:03:40 2007
@@ -553,8 +553,8 @@
// TRANSLATORS: proposal dialog help
string update_options_help = _("<p><b><big>Update Options</big></b>
Here you can choose how your system is going to be updated.
-Whether only installed packages should be updated or also new ones should be installed
-(the default selection) and whether unmaintained packages should be deleted.</p>");
+Choose whether only installed packages should be updated or also new ones should be installed
+(the default selection), and whether unmaintained packages should be deleted.");
ret = $[
"preformatted_proposal" : HTML::ListStart() + summary_text + HTML::ListEnd(),
Modified: trunk/update/src/modules/RootPart.ycp
URL: http://svn.opensuse.org/viewcvs/yast/trunk/update/src/modules/RootPart.ycp?…
==============================================================================
--- trunk/update/src/modules/RootPart.ycp (original)
+++ trunk/update/src/modules/RootPart.ycp Thu Dec 6 10:03:40 2007
@@ -424,7 +424,7 @@
// %1 is a device name such as /dev/hda5
_("The file system check of device %1 has failed.
-Would you like to continue in mounting the device?"), device
+Would you like to continue in the mounting the device?"), device
),
Label::ContinueButton(),
// button
@@ -924,11 +924,11 @@
// %2 with the recommended size
sformat (
_("Your /boot partition is too small (%1 MB).
-Recommended size is not less than %2 MB. It may happen that the
-new Kernel needn't fit it. It would be safer to enlarge that partition
-or even not to use the /boot partition at all.
+We recommend a size not less than %2 MB. It might happen, that the
+new Kernel does not fit, so it would be safer to either enlarge that partition
+or not to use the /boot partition at all.
-Would you like to continue in updating the current system?"),
+Would you like to continue updating the current system?"),
current_bs,
suggested_bs
)
--
To unsubscribe, e-mail: yast-commit+unsubscribe(a)opensuse.org
For additional commands, e-mail: yast-commit+help(a)opensuse.org
1
0

[yast-commit] r42751 - in /trunk/pkg-bindings/src: PkgModuleFunctions.h Source_Load.cc
by lslezak@svn.opensuse.org 06 Dec '07
by lslezak@svn.opensuse.org 06 Dec '07
06 Dec '07
Author: lslezak
Date: Thu Dec 6 08:33:40 2007
New Revision: 42751
URL: http://svn.opensuse.org/viewcvs/yast?rev=42751&view=rev
Log:
- removed obsoleted SourceLoadReceiver() function
Modified:
trunk/pkg-bindings/src/PkgModuleFunctions.h
trunk/pkg-bindings/src/Source_Load.cc
Modified: trunk/pkg-bindings/src/PkgModuleFunctions.h
URL: http://svn.opensuse.org/viewcvs/yast/trunk/pkg-bindings/src/PkgModuleFuncti…
==============================================================================
--- trunk/pkg-bindings/src/PkgModuleFunctions.h (original)
+++ trunk/pkg-bindings/src/PkgModuleFunctions.h Thu Dec 6 08:33:40 2007
@@ -49,8 +49,6 @@
#include <zypp/DiskUsageCounter.h>
#include <zypp/RepoInfo.h>
#include <zypp/RepoManager.h>
-#include <zypp/MediaSetAccess.h>
-#include <zypp/ProgressData.h>
#include <YRepo.h>
@@ -719,8 +717,6 @@
*/
PkgModuleFunctions ();
- bool SourceLoadReceiver(const zypp::ProgressData &progress);
-
/**
* Destructor.
*/
Modified: trunk/pkg-bindings/src/Source_Load.cc
URL: http://svn.opensuse.org/viewcvs/yast/trunk/pkg-bindings/src/Source_Load.cc?…
==============================================================================
--- trunk/pkg-bindings/src/Source_Load.cc (original)
+++ trunk/pkg-bindings/src/Source_Load.cc Thu Dec 6 08:33:40 2007
@@ -19,7 +19,7 @@
*/
/*
- File: $Id:$
+ File: $Id$
Author: Ladislav Slezák <lslezak(a)novell.com>
Summary: Functions for initializing the package manager
*/
@@ -91,24 +91,6 @@
return YCPList();
}
-bool PkgModuleFunctions::SourceLoadReceiver(const zypp::ProgressData &progress)
-{
- y2milestone("Source Load receiver: %lld (%lld%%)", progress.val(), progress.reportValue());
-
- // get the YCP callback handler for destroy event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_ProcessProgress);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- ycp_handler->appendParameter(YCPInteger(progress.reportValue()));
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-
- return true;
-}
-
/****************************************************************************************
* @builtin SourceLoad
*
--
To unsubscribe, e-mail: yast-commit+unsubscribe(a)opensuse.org
For additional commands, e-mail: yast-commit+help(a)opensuse.org
1
0
Author: lslezak
Date: Thu Dec 6 07:56:58 2007
New Revision: 42750
URL: http://svn.opensuse.org/viewcvs/yast?rev=42750&view=rev
Log:
- big files have been split - better maintenance and faster parallel compilation
Added:
trunk/pkg-bindings/src/Callbacks.YCP.cc
- copied, changed from r42663, trunk/pkg-bindings/src/Callbacks.YCP.h
trunk/pkg-bindings/src/Callbacks_Register.cc
- copied, changed from r42663, trunk/pkg-bindings/src/Callbacks.cc
trunk/pkg-bindings/src/Locale.cc
- copied, changed from r42212, trunk/pkg-bindings/src/PkgModuleFunctions.cc
trunk/pkg-bindings/src/PkgModuleFunctions_Register.cc
trunk/pkg-bindings/src/Source_Callbacks.cc
- copied, changed from r42708, trunk/pkg-bindings/src/Source.cc
trunk/pkg-bindings/src/Source_Create.cc
- copied, changed from r42708, trunk/pkg-bindings/src/Source.cc
trunk/pkg-bindings/src/Source_Download.cc
- copied, changed from r42708, trunk/pkg-bindings/src/Source.cc
trunk/pkg-bindings/src/Source_Get.cc
- copied, changed from r42708, trunk/pkg-bindings/src/Source.cc
trunk/pkg-bindings/src/Source_Installation.cc
- copied, changed from r42708, trunk/pkg-bindings/src/Source.cc
trunk/pkg-bindings/src/Source_Load.cc
- copied, changed from r42708, trunk/pkg-bindings/src/Source.cc
trunk/pkg-bindings/src/Source_Misc.cc
- copied, changed from r42708, trunk/pkg-bindings/src/Source.cc
trunk/pkg-bindings/src/Source_Resolvables.cc
- copied, changed from r42708, trunk/pkg-bindings/src/Source.cc
trunk/pkg-bindings/src/Source_Save.cc
- copied, changed from r42708, trunk/pkg-bindings/src/Source.cc
trunk/pkg-bindings/src/Source_Set.cc
- copied, changed from r42708, trunk/pkg-bindings/src/Source.cc
trunk/pkg-bindings/src/Y2PkgFunction.cc
- copied, changed from r42212, trunk/pkg-bindings/src/PkgModuleFunctions.cc
trunk/pkg-bindings/src/Y2PkgFunction.h
trunk/pkg-bindings/src/YRepo.cc
trunk/pkg-bindings/src/YRepo.h
Removed:
trunk/pkg-bindings/src/Source.cc
Modified:
trunk/pkg-bindings/src/Callbacks.YCP.h
trunk/pkg-bindings/src/Callbacks.cc
trunk/pkg-bindings/src/Makefile.am
trunk/pkg-bindings/src/PkgModuleFunctions.cc
trunk/pkg-bindings/src/PkgModuleFunctions.h
Copied: trunk/pkg-bindings/src/Callbacks.YCP.cc (from r42663, trunk/pkg-bindings/src/Callbacks.YCP.h)
URL: http://svn.opensuse.org/viewcvs/yast/trunk/pkg-bindings/src/Callbacks.YCP.c…
==============================================================================
--- trunk/pkg-bindings/src/Callbacks.YCP.h (original)
+++ trunk/pkg-bindings/src/Callbacks.YCP.cc Thu Dec 6 07:56:58 2007
@@ -19,229 +19,10 @@
(not intended to be distributed)
/-*/
-#ifndef PkgModuleCallbacksYCP_h
-#define PkgModuleCallbacksYCP_h
-#include <stack>
+#include "Callbacks.YCP.h"
-#include <y2util/stringutil.h>
-//#include <y2util/Date.h>
-//#include <y2util/FSize.h>
-
-#include <y2/Y2ComponentBroker.h>
-#include <y2/Y2Component.h>
-#include <y2/Y2Namespace.h>
-#include <y2/Y2Function.h>
-
-#include "ycpTools.h"
-#include "Callbacks.h"
-
-//#include <ycp/y2log.h>
-
-using namespace std;
-
-///////////////////////////////////////////////////////////////////
-//
-// CLASS NAME : PkgModuleFunctions::CallbackHandler::YCPCallbacks
-/**
- * @short Stores YCPCallback related data and communicates with Y2ComponentBroker
- *
- * For each YCPCallback it's data, identified by a <CODE>@ref CBid</CODE>,
- * are stored in maps.
- *
- * To invoke a YCPCallback:
- * <PRE>
- * YCPTerm callback = createCallback( CB_PatchProgress ); // create callback Term
- * callback->add( YCPInteger ( percent ) ); // add arguments
- * callback->add( YCPString ( pkg ) );
- * bool result = evaluateBool( callback ); // evaluate
- * </PRE>
- **/
-class PkgModuleFunctions::CallbackHandler::YCPCallbacks
-{
- public:
-
- /**
- * Unique id for each YCPCallback we may have to trigger.
- * On changes here, adapt @ref cbName.
- **/
- enum CBid {
- CB_StartRebuildDb, CB_ProgressRebuildDb, CB_NotifyRebuildDb, CB_StopRebuildDb,
- CB_StartConvertDb, CB_ProgressConvertDb, CB_NotifyConvertDb, CB_StopConvertDb,
- CB_StartScanDb, CB_ProgressScanDb, CB_ErrorScanDb, CB_DoneScanDb,
- CB_StartProvide, CB_ProgressProvide, CB_DoneProvide,
- CB_StartPackage, CB_ProgressPackage, CB_DonePackage,
-
- CB_SourceCreateStart, CB_SourceCreateProgress, CB_SourceCreateError, CB_SourceCreateEnd,
- CB_SourceCreateInit, CB_SourceCreateDestroy,
-
- CB_ProgressStart, CB_ProgressProgress, CB_ProgressDone,
-
- CB_StartSourceRefresh, CB_ErrorSourceRefresh, CB_DoneSourceRefresh, CB_ProgressSourceRefresh,
- CB_StartDeltaDownload, CB_ProgressDeltaDownload, CB_ProblemDeltaDownload,
- CB_StartDeltaApply, CB_ProgressDeltaApply, CB_ProblemDeltaApply,
- CB_StartPatchDownload, CB_ProgressPatchDownload, CB_ProblemPatchDownload,
- CB_FinishDeltaDownload, CB_FinishDeltaApply, CB_FinishPatchDownload,
- CB_StartDownload, CB_ProgressDownload, CB_DoneDownload, CB_InitDownload, CB_DestDownload,
-
- CB_SourceProbeStart, CB_SourceProbeFailed, CB_SourceProbeSucceeded, CB_SourceProbeEnd, CB_SourceProbeProgress, CB_SourceProbeError,
- CB_SourceReportStart, CB_SourceReportProgress, CB_SourceReportError, CB_SourceReportEnd, CB_SourceReportInit, CB_SourceReportDestroy,
-
- CB_ScriptStart, CB_ScriptProgress, CB_ScriptProblem, CB_ScriptFinish,
- CB_Message,
-
- CB_Authentication,
-
- CB_MediaChange,
- CB_SourceChange,
- CB_ResolvableReport,
- CB_ImportGpgKey,
- CB_AcceptNonTrustedGpgKey,
- CB_AcceptUnknownGpgKey,
- CB_AcceptUnsignedFile,
- CB_AcceptFileWithoutChecksum,
- CB_AcceptVerificationFailed,
- CB_AcceptWrongDigest, CB_AcceptUnknownDigest,
- CB_TrustedKeyAdded,
- CB_TrustedKeyRemoved,
-
- CB_ProcessStart,
- CB_ProcessNextStage,
- CB_ProcessProgress,
- CB_ProcessFinished,
- };
-
- /**
- * Returns the enum name without the leading "CB_"
- * (e.g. "StartProvide" for CB_StartProvide). Should
- * be in sync with @ref CBid.
- **/
- static string cbName( CBid id_r ) {
- switch ( id_r ) {
-#define ENUM_OUT(N) case CB_##N: return #N
- ENUM_OUT( StartRebuildDb );
- ENUM_OUT( ProgressRebuildDb );
- ENUM_OUT( NotifyRebuildDb );
- ENUM_OUT( StopRebuildDb );
- ENUM_OUT( StartConvertDb );
- ENUM_OUT( ProgressConvertDb );
- ENUM_OUT( NotifyConvertDb );
- ENUM_OUT( StopConvertDb );
- ENUM_OUT( StartScanDb );
- ENUM_OUT( ProgressScanDb );
- ENUM_OUT( ErrorScanDb );
- ENUM_OUT( DoneScanDb );
-
- ENUM_OUT( StartProvide );
- ENUM_OUT( ProgressProvide );
- ENUM_OUT( DoneProvide );
- ENUM_OUT( StartPackage );
- ENUM_OUT( ProgressPackage );
- ENUM_OUT( DonePackage );
- ENUM_OUT( StartDownload );
- ENUM_OUT( ProgressDownload );
- ENUM_OUT( DoneDownload );
- ENUM_OUT( InitDownload );
- ENUM_OUT( DestDownload );
-
- ENUM_OUT( ScriptStart );
- ENUM_OUT( ScriptProgress );
- ENUM_OUT( ScriptProblem );
- ENUM_OUT( ScriptFinish );
- ENUM_OUT( Message );
-
- ENUM_OUT( Authentication );
-
- ENUM_OUT( SourceCreateStart );
- ENUM_OUT( SourceCreateProgress );
- ENUM_OUT( SourceCreateError );
- ENUM_OUT( SourceCreateEnd );
- ENUM_OUT( SourceCreateInit );
- ENUM_OUT( SourceCreateDestroy );
-
- ENUM_OUT( SourceProbeStart );
- ENUM_OUT( SourceProbeFailed );
- ENUM_OUT( SourceProbeSucceeded );
- ENUM_OUT( SourceProbeEnd );
- ENUM_OUT( SourceProbeProgress );
- ENUM_OUT( SourceProbeError );
-
- ENUM_OUT( SourceReportStart );
- ENUM_OUT( SourceReportProgress );
- ENUM_OUT( SourceReportError );
- ENUM_OUT( SourceReportEnd );
- ENUM_OUT( SourceReportInit );
- ENUM_OUT( SourceReportDestroy );
-
- ENUM_OUT( ProgressStart );
- ENUM_OUT( ProgressProgress );
- ENUM_OUT( ProgressDone );
-
- ENUM_OUT( StartSourceRefresh );
- ENUM_OUT( ErrorSourceRefresh );
- ENUM_OUT( DoneSourceRefresh );
- ENUM_OUT( ProgressSourceRefresh );
- ENUM_OUT( StartDeltaDownload );
- ENUM_OUT( ProgressDeltaDownload );
- ENUM_OUT( ProblemDeltaDownload );
- ENUM_OUT( StartDeltaApply );
- ENUM_OUT( ProgressDeltaApply );
- ENUM_OUT( ProblemDeltaApply );
- ENUM_OUT( StartPatchDownload );
- ENUM_OUT( ProgressPatchDownload );
- ENUM_OUT( ProblemPatchDownload );
- ENUM_OUT( FinishDeltaDownload );
- ENUM_OUT( FinishDeltaApply );
- ENUM_OUT( FinishPatchDownload );
- ENUM_OUT( MediaChange );
- ENUM_OUT( SourceChange );
- ENUM_OUT( ResolvableReport );
- ENUM_OUT( ImportGpgKey );
- ENUM_OUT( AcceptNonTrustedGpgKey );
- ENUM_OUT( AcceptUnknownGpgKey );
- ENUM_OUT( AcceptUnsignedFile );
- ENUM_OUT( AcceptVerificationFailed );
- ENUM_OUT( AcceptFileWithoutChecksum );
- ENUM_OUT( TrustedKeyAdded );
- ENUM_OUT( TrustedKeyRemoved );
- ENUM_OUT( AcceptWrongDigest );
- ENUM_OUT( AcceptUnknownDigest );
-
- ENUM_OUT( ProcessStart );
- ENUM_OUT( ProcessNextStage );
- ENUM_OUT( ProcessProgress );
- ENUM_OUT( ProcessFinished );
-#undef ENUM_OUT
- // no default! let compiler warn missing values
- }
- return stringutil::form( "CBid(%d)", id_r );
- }
-
- private:
-
- struct CBdata
- {
- CBdata (string module, string symbol, Y2Namespace* component)
- : module (module), symbol (symbol), component (component)
- { }
-
- const string module, symbol;
- Y2Namespace* component;
- };
-
- typedef map <CBid, stack <CBdata> > _cbdata_t;
- _cbdata_t _cbdata;
-
- public:
-
- /**
- * Constructor.
- **/
- YCPCallbacks( )
- {}
-
-
- void popCallback( CBid id_r ) {
+ void PkgModuleFunctions::CallbackHandler::YCPCallbacks::popCallback( CBid id_r ) {
_cbdata_t::iterator tmp1 = _cbdata.find(id_r);
if (tmp1 != _cbdata.end() && !tmp1->second.empty())
tmp1->second.pop();
@@ -250,7 +31,7 @@
/**
* Set a YCPCallbacks data from string "module::symbol"
**/
- void setCallback( CBid id_r, const string & name_r ) {
+ void PkgModuleFunctions::CallbackHandler::YCPCallbacks::setCallback( CBid id_r, const string & name_r ) {
y2debug ("Registering callback %s", name_r.c_str ());
string::size_type colonpos = name_r.find("::");
if ( colonpos != string::npos ) {
@@ -285,7 +66,7 @@
/**
* Set a YCPCallbacks data according to args_r.
**/
- bool setCallback( CBid id_r, const YCPString & args ) {
+ bool PkgModuleFunctions::CallbackHandler::YCPCallbacks::setCallback( CBid id_r, const YCPString & args ) {
string name = args->value();
setCallback( id_r, name );
return true;
@@ -294,7 +75,7 @@
* Set the YCPCallback according to args_r.
* @return YCPVoid on success, otherwise YCPError.
**/
- YCPValue setYCPCallback( CBid id_r, const YCPString & args_r ) {
+ YCPValue PkgModuleFunctions::CallbackHandler::YCPCallbacks::setYCPCallback( CBid id_r, const YCPString & args_r ) {
if (!args_r->value().empty ())
{
if ( ! setCallback( id_r, args_r ) ) {
@@ -312,17 +93,15 @@
* @return Whether the YCPCallback is set. If not, there's
* no need to create and evaluate it.
**/
- bool isSet( CBid id_r ) const {
+ bool PkgModuleFunctions::CallbackHandler::YCPCallbacks::isSet( CBid id_r ) const {
const _cbdata_t::const_iterator tmp1 = _cbdata.find(id_r);
return tmp1 != _cbdata.end() && !tmp1->second.empty();
}
- public:
-
/**
* @return The YCPCallback term, ready to append any arguments.
**/
- Y2Function* createCallback( CBid id_r ) const {
+ Y2Function* PkgModuleFunctions::CallbackHandler::YCPCallbacks::createCallback( CBid id_r ) const {
const _cbdata_t::const_iterator tmp1 = _cbdata.find(id_r);
if (tmp1 == _cbdata.end() || tmp1->second.empty())
return NULL;
@@ -347,111 +126,3 @@
return func;
}
- public:
-
- /**
- * @short Convenience base class for YCPCallback sender
- *
- * A functional interface for sending YCPCallbacks with well known arguments
- * and return values is desirable. Esp. for YCPcallbacks triggered from
- * multiple recipients. Currently each recipient has to implememt correct
- * number and type of arguments, as well as the returned type. That's bad
- * if something changes. As soon as YCPCallbacks provides them (as const methods),
- * ZyppRecipients::Recipient should no longer inherit Send, but provide
- * an easy access to RecipientCtl::_ycpcb.
- **/
- class Send {
- public:
- /**
- * @short Convenience class for YCPCallback sending
- **/
- struct CB {
- const Send & _send;
- CBid _id;
- bool _set;
- Y2Function* _func;
- YCPValue _result;
- CB( const Send & send_r, CBid func )
- : _send( send_r )
- , _id( func )
- , _set( _send.ycpcb().isSet( func ) )
- , _func( _send.ycpcb().createCallback( func ) )
- , _result( YCPVoid() )
- {}
-
- ~CB ()
- {
- if (_func) delete _func;
- }
-
- CB & addStr( const string & arg ) { if (_func != NULL) _func->appendParameter( YCPString( arg ) ); return *this; }
- CB & addStr( const zypp::Pathname & arg ) { return addStr( arg.asString() ); }
- CB & addStr( const zypp::Url & arg ) { return addStr( arg.asString() ); }
-
- CB & addInt( long long arg ) { if (_func != NULL) _func->appendParameter( YCPInteger( arg ) ); return *this; }
-
- CB & addBool( bool arg ) { if (_func != NULL) _func->appendParameter( YCPBoolean( arg ) ); return *this; }
-
- CB & addMap( YCPMap arg ) { if (_func != NULL) _func->appendParameter( arg ); return *this; }
-
- bool isStr() const { return _result->isString(); }
- bool isInt() const { return _result->isInteger(); }
- bool isBool() const { return _result->isBoolean(); }
-
- bool expecting( YCPValueType exp_r ) const {
- if ( _result->valuetype() == exp_r )
- return true;
- y2internal ("Wrong return type %s: Expected %s", Type::vt2type(_result->valuetype())->toString().c_str(), Type::vt2type(exp_r)->toString().c_str());
- return false;
- }
-
- bool evaluate() {
- if ( _set && _func ) {
- y2debug ("Evaluating callback (registered funciton: %s)", _func->name().c_str());
- _result = _func->evaluateCall ();
-
- delete _func;
- _func = _send.ycpcb().createCallback( _id );
- return true;
- }
- return false;
- }
-
- bool evaluate( YCPValueType exp_r ) {
- return evaluate() && expecting( exp_r );
- }
-
- string evaluateStr( const string & def_r = "" ) {
- return evaluate( YT_STRING ) ? _result->asString()->value() : def_r;
- }
-
- string evaluateSymbol( const string & def_r = "" ) {
- return evaluate( YT_SYMBOL ) ? _result->asSymbol()->symbol() : def_r;
- }
-
- long long evaluateInt( const long long & def_r = 0 ) {
- return evaluate( YT_INTEGER ) ? _result->asInteger()->value() : def_r;
- }
-
- bool evaluateBool( const bool & def_r = false ) {
- return evaluate( YT_BOOLEAN ) ? _result->asBoolean()->value() : def_r;
- }
-
- YCPMap evaluateMap( const YCPMap def_r = YCPMap())
- {
- return evaluate( YT_MAP ) ? _result->asMap() : def_r;
- }
- };
- private:
- const YCPCallbacks & _ycpcb;
- public:
- Send( const YCPCallbacks & ycpcb_r ) : _ycpcb( ycpcb_r ) {}
- virtual ~Send() {}
- const YCPCallbacks & ycpcb() const { return _ycpcb; }
- CB ycpcb( CBid func ) const { return CB( *this, func ); }
- };
-};
-
-///////////////////////////////////////////////////////////////////
-
-#endif // PkgModuleCallbacksYCP_h
Modified: trunk/pkg-bindings/src/Callbacks.YCP.h
URL: http://svn.opensuse.org/viewcvs/yast/trunk/pkg-bindings/src/Callbacks.YCP.h…
==============================================================================
--- trunk/pkg-bindings/src/Callbacks.YCP.h (original)
+++ trunk/pkg-bindings/src/Callbacks.YCP.h Thu Dec 6 07:56:58 2007
@@ -241,111 +241,36 @@
{}
- void popCallback( CBid id_r ) {
- _cbdata_t::iterator tmp1 = _cbdata.find(id_r);
- if (tmp1 != _cbdata.end() && !tmp1->second.empty())
- tmp1->second.pop();
- }
+ void popCallback( CBid id_r );
/**
* Set a YCPCallbacks data from string "module::symbol"
**/
- void setCallback( CBid id_r, const string & name_r ) {
- y2debug ("Registering callback %s", name_r.c_str ());
- string::size_type colonpos = name_r.find("::");
- if ( colonpos != string::npos ) {
-
- string module = name_r.substr ( 0, colonpos );
- string symbol = name_r.substr ( colonpos + 2 );
-
- Y2Component *c = Y2ComponentBroker::getNamespaceComponent (module.c_str());
- if (c == NULL)
- {
- ycp2error ("No component can provide namespace %s for a callback of %s (callback id %d)",
- module.c_str (), symbol.c_str (), id_r);
- return;
- }
-
- Y2Namespace *ns = c->import (module.c_str ());
- if (ns == NULL)
- {
- y2error ("Component %p could not provide namespace %s for a callback of %s",
- c, module.c_str (), symbol.c_str ());
- return;
- }
-
- // ensure it is an initialized namespace
- ns->initialize ();
-
- _cbdata[id_r].push (CBdata (module, symbol, ns));
- } else {
- ycp2error ("Callback must be a part of a namespace");
- }
- }
+ void setCallback( CBid id_r, const string & name_r );
+
/**
* Set a YCPCallbacks data according to args_r.
**/
- bool setCallback( CBid id_r, const YCPString & args ) {
- string name = args->value();
- setCallback( id_r, name );
- return true;
- }
+ bool setCallback( CBid id_r, const YCPString & args );
+
/**
* Set the YCPCallback according to args_r.
* @return YCPVoid on success, otherwise YCPError.
**/
- YCPValue setYCPCallback( CBid id_r, const YCPString & args_r ) {
- if (!args_r->value().empty ())
- {
- if ( ! setCallback( id_r, args_r ) ) {
- return YCPError( string("Bad args to Pkg::Callback") + cbName( id_r ) );
- }
- }
- else
- {
- popCallback( id_r );
- }
- return YCPVoid();
- }
+ YCPValue setYCPCallback( CBid id_r, const YCPString & args_r );
/**
* @return Whether the YCPCallback is set. If not, there's
* no need to create and evaluate it.
**/
- bool isSet( CBid id_r ) const {
- const _cbdata_t::const_iterator tmp1 = _cbdata.find(id_r);
- return tmp1 != _cbdata.end() && !tmp1->second.empty();
- }
+ bool isSet( CBid id_r ) const;
public:
/**
* @return The YCPCallback term, ready to append any arguments.
**/
- Y2Function* createCallback( CBid id_r ) const {
- const _cbdata_t::const_iterator tmp1 = _cbdata.find(id_r);
- if (tmp1 == _cbdata.end() || tmp1->second.empty())
- return NULL;
- const CBdata& tmp2 = tmp1->second.top();
-
- string module = tmp2.module;
- string name = tmp2.symbol;
- Y2Namespace *ns = tmp2.component;
- if (ns == NULL)
- {
- y2error ("No namespace %s for a callback of %s", module.c_str (), name.c_str ());
- return NULL;
- }
-
- Y2Function* func = ns->createFunctionCall (name, Type::Unspec); // FIXME: here we can setup the type check
- if (func == NULL)
- {
- ycp2error ("Cannot find function %s in module %s as a callback", name.c_str (), module.c_str());
- return NULL;
- }
-
- return func;
- }
+ Y2Function* createCallback( CBid id_r ) const;
public:
Modified: trunk/pkg-bindings/src/Callbacks.cc
URL: http://svn.opensuse.org/viewcvs/yast/trunk/pkg-bindings/src/Callbacks.cc?re…
==============================================================================
--- trunk/pkg-bindings/src/Callbacks.cc (original)
+++ trunk/pkg-bindings/src/Callbacks.cc Thu Dec 6 07:56:58 2007
@@ -1875,688 +1875,3 @@
delete &_ycpCallbacks;
}
-///////////////////////////////////////////////////////////////////
-//
-// CLASS NAME : PkgModuleFunctions
-//
-// Set YCPCallbacks. _ycpCallbacks
-//
-///////////////////////////////////////////////////////////////////
-
-#define SET_YCP_CB(E,A) _callbackHandler._ycpCallbacks.setYCPCallback( CallbackHandler::YCPCallbacks::E, A );
-
-YCPValue PkgModuleFunctions::CallbackStartProvide( const YCPString& args ) {
- return SET_YCP_CB( CB_StartProvide, args );
-}
-YCPValue PkgModuleFunctions::CallbackProgressProvide( const YCPString& args ) {
- return SET_YCP_CB( CB_ProgressProvide, args );
-}
-YCPValue PkgModuleFunctions::CallbackDoneProvide( const YCPString& args ) {
- return SET_YCP_CB( CB_DoneProvide, args );
-}
-
-YCPValue PkgModuleFunctions::CallbackStartPackage( const YCPString& args ) {
- return SET_YCP_CB( CB_StartPackage, args );
-}
-YCPValue PkgModuleFunctions::CallbackProgressPackage( const YCPString& args ) {
- return SET_YCP_CB( CB_ProgressPackage, args );
-}
-YCPValue PkgModuleFunctions::CallbackDonePackage( const YCPString& args ) {
- return SET_YCP_CB( CB_DonePackage, args );
-}
-
-YCPValue PkgModuleFunctions::CallbackResolvableReport( const YCPString& args ) {
- return SET_YCP_CB( CB_ResolvableReport, args );
-}
-
-/**
- * @builtin CallbackImportGpgKey
- * @short Register callback function
- * @param string args Name of the callback handler function. Required callback prototype is <code>boolean(string keyid, string keyname, string keydetails)</code>. The callback function should ask user whether the key is trusted, returned true value means the key is trusted.
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackImportGpgKey( const YCPString& args ) {
- return SET_YCP_CB( CB_ImportGpgKey, args );
-}
-
-/**
- * @builtin CallbackAcceptUnknownGpgKey
- * @short Register callback function
- * @param string args Name of the callback handler function. Required callback prototype is <code>boolean(string filename, string keyid)</code>. The callback function should ask user whether the unknown key can be accepted, returned true value means to accept the key.
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackAcceptUnknownGpgKey( const YCPString& args ) {
- return SET_YCP_CB( CB_AcceptUnknownGpgKey, args );
-}
-
-/**
- * @builtin CallbackAcceptNonTrustedGpgKey
- * @short Register callback function
- * @param string args Name of the callback handler function. Required callback prototype is <code>boolean(string filename, string keyid, string keyname, string fingerprint)</code>. The callback function should ask user whether the unknown key can be accepted, returned true value means to accept the file.
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackAcceptNonTrustedGpgKey( const YCPString& args ) {
- return SET_YCP_CB( CB_AcceptNonTrustedGpgKey, args );
-}
-
-/**
- * @builtin CallbackAcceptUnsignedFile
- * @short Register callback function
- * @param string args Name of the callback handler function. Required callback prototype is <code>boolean(string filename)</code>. The callback function should ask user whether the unsigned file can be accepted, returned true value means to accept the file.
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackAcceptUnsignedFile( const YCPString& args ) {
- return SET_YCP_CB( CB_AcceptUnsignedFile, args );
-}
-
-/**
- * @builtin CallbackAcceptFileWithoutChecksum
- * @short Register callback function
- * @param string args Name of the callback handler function. Required callback prototype is <code>boolean(string filename)</code>. The callback function should ask user whether the unsigned file can be accepted, returned true value means to accept the file.
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackAcceptFileWithoutChecksum( const YCPString& args ) {
- return SET_YCP_CB( CB_AcceptFileWithoutChecksum, args );
-}
-
-/**
- * @builtin CallbackAcceptVerificationFailed
- * @short Register callback function
- * @param string args Name of the callback handler function. Required callback prototype is <code>boolean(string filename, string keyid, string keyname)</code>. The callback function should ask user whether the unsigned file can be accepted, returned true value means to accept the file.
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackAcceptVerificationFailed( const YCPString& args ) {
- return SET_YCP_CB( CB_AcceptVerificationFailed, args );
-}
-
-/**
- * @builtin CallbackAcceptWrongDigest
- * @short Register callback function
- * @param string args Name of the callback handler function. Required callback prototype is <code>boolean(string filename, string requested_digest, string found_digest)</code>. The callback function should ask user whether the wrong digest can be accepted, returned true value means to accept the file.
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackAcceptWrongDigest( const YCPString& func)
-{
- return SET_YCP_CB( CB_AcceptWrongDigest, func );
-}
-
-/**
- * @builtin CallbackAcceptUnknownDigest
- * @short Register callback function
- * @param string args Name of the callback handler function. Required callback prototype is <code>boolean(string filename, string name)</code>. The callback function should ask user whether the uknown digest can be accepted, returned true value means to accept the digest.
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackAcceptUnknownDigest( const YCPString& func)
-{
- return SET_YCP_CB( CB_AcceptUnknownDigest, func );
-}
-
-/**
- * @builtin CallbackTrustedKeyAdded
- * @short Register callback function
- * @param string args Name of the callback handler function. Required callback prototype is <code>void(string keyid, string keyname)</code>. The callback function should inform user that a trusted key has been added.
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackTrustedKeyAdded( const YCPString& args ) {
- return SET_YCP_CB( CB_TrustedKeyAdded, args );
-}
-
-/**
- * @builtin CallbackTrustedKeyRemoved
- * @short Register callback function
- * @param string args Name of the callback handler function. Required callback prototype is <code>void(string keyid, string keyname)</code>. The callback function should inform user that a trusted key has been removed.
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackTrustedKeyRemoved( const YCPString& args ) {
- return SET_YCP_CB( CB_TrustedKeyRemoved, args );
-}
-
-YCPValue PkgModuleFunctions::CallbackMediaChange( const YCPString& args ) {
- // FIXME: Allow omission of 'src' argument in 'src, name'. Since we can
- // handle one callback function at most, passing a src argument
- // implies a per-source callback which isn't implemented anyway.
- return SET_YCP_CB( CB_MediaChange, args );
-}
-
-YCPValue PkgModuleFunctions::CallbackSourceChange( const YCPString& args ) {
- return SET_YCP_CB( CB_SourceChange, args );
-}
-
-
-YCPValue PkgModuleFunctions::CallbackYouProgress( const YCPString& args ) {
- y2warning("Pkg::CallbackYouProgress is obsoleted, do not use it (empty implementation)!");
- return YCPVoid();
-}
-
-YCPValue PkgModuleFunctions::CallbackYouPatchProgress( const YCPString& args ) {
- y2warning("Pkg::CallbackYouPatchProgress is obsoleted, do not use it (empty implementation)!");
- return YCPVoid();
-}
-
-YCPValue PkgModuleFunctions::CallbackYouError( const YCPString& args ) {
- y2warning("Pkg::CallbackYouError is obsoleted, do not use it (empty implementation)!");
- return YCPVoid();
-}
-
-YCPValue PkgModuleFunctions::CallbackYouMessage( const YCPString& args ) {
- y2warning("Pkg::CallbackYouMessage is obsoleted, do not use it (empty implementation)!");
- return YCPVoid();
-}
-
-YCPValue PkgModuleFunctions::CallbackYouLog( const YCPString& args ) {
- y2warning("Pkg::CallbackYouLog is obsoleted, do not use it (empty implementation)!");
- return YCPVoid();
-}
-
-YCPValue PkgModuleFunctions::CallbackYouExecuteYcpScript( const YCPString& args ) {
- y2warning("Pkg::CallbackYouExecuteYcpScript is obsoleted, do not use it (empty implementation)!");
- return YCPVoid();
-}
-YCPValue PkgModuleFunctions::CallbackYouScriptProgress( const YCPString& args ) {
- y2warning("Pkg::CallbackYouScriptProgress is obsoleted, do not use it (empty implementation)!");
- return YCPVoid();
-}
-
-YCPValue PkgModuleFunctions::CallbackStartRebuildDb( const YCPString& args ) {
- return SET_YCP_CB( CB_StartRebuildDb, args );
-}
-YCPValue PkgModuleFunctions::CallbackProgressRebuildDb( const YCPString& args ) {
- return SET_YCP_CB( CB_ProgressRebuildDb, args );
-}
-YCPValue PkgModuleFunctions::CallbackNotifyRebuildDb( const YCPString& args ) {
- return SET_YCP_CB( CB_NotifyRebuildDb, args );
-}
-YCPValue PkgModuleFunctions::CallbackStopRebuildDb( const YCPString& args ) {
- return SET_YCP_CB( CB_StopRebuildDb, args );
-}
-
-
-
-/**
- * @builtin CallbackStartScanDb
- * @short Register callback function
- * @param string func Name of the callback handler function. Required callback prototype is <code>void()</code>. The callback function is evaluated when the RPM DB reading has been started.
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackStartScanDb( const YCPString& args ) {
- return SET_YCP_CB( CB_StartScanDb, args );
-}
-/**
- * @builtin CallbackProgressScanDb
- * @short Register callback function
- * @param string func Name of the callback handler function. Required callback prototype is <code>boolean(integer percent)</code>. The callback function is evaluated during RPM DB reading.
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackProgressScanDb( const YCPString& args ) {
- return SET_YCP_CB( CB_ProgressScanDb, args );
-}
-/**
- * @builtin CallbackErrorScanDb
- * @short Register callback function
- * @param string func Name of the callback handler function. Required callback prototype is <code>void(integer error_code, string description)</code>. The callback function is evaluated when an error occurrs during RPM DB reading. error_code 0 means no error.
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackErrorScanDb( const YCPString& args ) {
- return SET_YCP_CB( CB_ErrorScanDb, args );
-}
-/**
- * @builtin CallbackDoneScanDb
- * @short Register callback function
- * @param string func Name of the callback handler function. Required callback prototype is <code>void(integer error_code, string description)</code>. The callback function is evaluated when RPM DB reading is finished. error_code 0 means no error.
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackDoneScanDb( const YCPString& args ) {
- return SET_YCP_CB( CB_DoneScanDb, args );
-}
-
-
-YCPValue PkgModuleFunctions::CallbackStartConvertDb( const YCPString& args ) {
- return SET_YCP_CB( CB_StartConvertDb, args );
-}
-YCPValue PkgModuleFunctions::CallbackProgressConvertDb( const YCPString& args ) {
- return SET_YCP_CB( CB_ProgressConvertDb, args );
-}
-YCPValue PkgModuleFunctions::CallbackNotifyConvertDb( const YCPString& args ) {
- return SET_YCP_CB( CB_NotifyConvertDb, args );
-}
-YCPValue PkgModuleFunctions::CallbackStopConvertDb( const YCPString& args ) {
- return SET_YCP_CB( CB_StopConvertDb, args );
-}
-
-
-/**
- * @builtin CallbackStartDeltaDownload
- * @short Register callback function
- * @param string func Name of the callback handler function. Required callback prototype is <code>void(string filename, integer download_size)</code>. If the download size is unknown download_size is 0. The callback function is evaluated when a delta RPM download has been started.
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackStartDeltaDownload( const YCPString& func ) {
- return SET_YCP_CB( CB_StartDeltaDownload, func );
-}
-
-/**
- * @builtin CallbackProgressDeltaDownload
- * @short Register callback function
- * @param string func Name of the callback handler function. Required callback prototype is <code>boolean (integer value)</code>. The callback function is evaluated when more than 5% of the size has been downloaded since the last evaluation. If the handler returns false the download is aborted.
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackProgressDeltaDownload( const YCPString& func ) {
- return SET_YCP_CB( CB_ProgressDeltaDownload, func );
-}
-
-/**
- * @builtin CallbackProblemDeltaDownload
- * @short Register callback function
- * @param string func Name of the callback handler function. Required callback prototype is <code>void(string description)</code>. The callback function should inform user that a problem has occurred during delta file download. This is not fatal, it still may be possible to download the full RPM instead.
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackProblemDeltaDownload( const YCPString& func ) {
- return SET_YCP_CB( CB_ProblemDeltaDownload, func );
-}
-
-/**
- * @builtin CallbackStartDeltaApply
- * @short Register callback function
- * @param string func Name of the callback handler function. Required callback prototype is <code>void(string filename)</code>. The callback function should inform user that a delta application has been started.
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackStartDeltaApply( const YCPString& func ) {
- return SET_YCP_CB( CB_StartDeltaApply, func );
-}
-
-/**
- * @builtin CallbackProgressDeltaApply
- * @short Register callback function
- * @param string func Name of the callback handler function. Required callback prototype is <code>void(integer value)</code>. The callback function is evaluated when more than 5% of the delta size has been applied since the last evaluation.
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackProgressDeltaApply( const YCPString& func ) {
- return SET_YCP_CB( CB_ProgressDeltaApply, func );
-}
-
-/**
- * @builtin CallbackProblemDeltaApply
- * @short Register callback function
- * @param string func Name of the callback handler function. Required callback prototype is <code>void(string description)</code>. The callback function should inform user that a problem has occurred during delta file application. This is not fatal, it still may be possible to use the full RPM instead.
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackProblemDeltaApply( const YCPString& func ) {
- return SET_YCP_CB( CB_ProblemDeltaApply, func );
-}
-
-/**
- * @builtin CallbackStartPatchDownload
- * @short Register callback function
- * @param string func Name of the callback handler function. Required callback prototype is <code>void(string filename, integer download_size)</code>. If the download size is unknown download_size is 0. The callback function is evaluated when a patch download has been started.
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackStartPatchDownload( const YCPString& func ) {
- return SET_YCP_CB( CB_StartPatchDownload, func );
-}
-
-/**
- * @builtin CallbackProgressPatchDownload
- * @short Register callback function
- * @param string func Name of the callback handler function. Required callback prototype is <code>boolean(integer value)</code>. The callback function is evaluated when more than 5% of the patch size has been downloaded since the last evaluation. If the handler returns false the download is aborted.
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackProgressPatchDownload( const YCPString& func ) {
- return SET_YCP_CB( CB_ProgressPatchDownload, func );
-}
-
-/**
- * @builtin CallbackProblemPatchDownload
- * @short Register callback function
- * @param string func Name of the callback handler function. Required callback prototype is <code>void(string description)</code>. The callback function should inform user that a problem has occurred during download of the patch.
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackProblemPatchDownload( const YCPString& func ) {
- return SET_YCP_CB( CB_ProblemPatchDownload, func );
-}
-
-
-/**
- * @builtin CallbackFinishDeltaDownload
- * @short Register callback function
- * @param string func Name of the callback handler function. Required callback prototype is <code>void()</code>. The callback function is evaluated when the delta download has been finished.
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackFinishDeltaDownload( const YCPString& func)
-{
- return SET_YCP_CB( CB_FinishDeltaDownload, func );
-}
-
-/**
- * @builtin CallbackFinishDeltaApply
- * @short Register callback function
- * @param string func Name of the callback handler function. Required callback prototype is <code>void()</code>. The callback function is evaluated when the delta download has been applied.
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackFinishDeltaApply( const YCPString& func)
-{
- return SET_YCP_CB( CB_FinishDeltaApply, func );
-}
-
-/**
- * @builtin CallbackFinishPatchDownload
- * @short Register callback function
- * @param string func Name of the callback handler function. Required callback prototype is <code>void()</code>. The callback function is evaluated when the patch download has been finished.
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackFinishPatchDownload( const YCPString& func)
-{
- return SET_YCP_CB( CB_FinishPatchDownload, func );
-}
-
-
-/**
- * @builtin CallbackSourceCreateStart
- * @short Register callback function
- * @param string func Name of the callback handler function. Required callback prototype is <code>void(string url)</code>. The callback is evaluated when a source creation has been started.
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackSourceCreateStart( const YCPString& func)
-{
- return SET_YCP_CB( CB_SourceCreateStart, func );
-}
-
-
-/**
- * @builtin CallbackSourceProgressData
- * @short Register callback function
- * @param string func Name of the callback handler function. Required callback prototype is <code>boolean(integer value)</code>. The callback function is evaluated when more than 5% of the data has been processed since the last evaluation. If the handler returns false the download is aborted.
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackSourceCreateProgress( const YCPString& func)
-{
- return SET_YCP_CB( CB_SourceCreateProgress, func );
-}
-
-/**
- * @builtin CallbackSourceCreateError
- * @short Register callback function
- * @param string func Name of the callback handler function. Required callback prototype is <code>string(string url, string err_code, string description)</code>. err_code is "NO_ERROR", "NOT_FOUND" (the URL was not found), "IO" (I/O error) or "INVALID" (the source is not valid). The callback function must return "ABORT" or "RETRY". The callback function is evaluated when an error occurrs during creation of the source.
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackSourceCreateError( const YCPString& func)
-{
- return SET_YCP_CB( CB_SourceCreateError, func );
-}
-
-/**
- * @builtin CallbackSourceCreateEnd
- * @short Register callback function
- * @param string func Name of the callback handler function. Required callback prototype is <code>void(string url, string err_code, string description)</code>. err_code is "NO_ERROR", "NOT_FOUND" (the URL was not found), "IO" (I/O error) or "INVALID" (the source is not valid). The callback function is evaluated when creation of the source has been finished.
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackSourceCreateEnd( const YCPString& func)
-{
- return SET_YCP_CB( CB_SourceCreateEnd, func );
-}
-
-
-
-
-/**
- * @builtin CallbackSourceProbeStart
- * @short Register callback function
- * @param string func Name of the callback handler function. Required callback prototype is <code>void(string url)</code>. The callback function is evaluated when source probing has been started.
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackSourceProbeStart( const YCPString& func)
-{
- return SET_YCP_CB( CB_SourceProbeStart, func );
-}
-
-/**
- * @builtin CallbackSourceProbeFailed
- * @short Register callback function
- * @param string func Name of the callback handler function. Required callback prototype is <code>void(string url, string type)</code>. The callback function is evaluated when the probed source has different type.
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackSourceProbeFailed( const YCPString& func)
-{
- return SET_YCP_CB( CB_SourceProbeFailed, func );
-}
-
-/**
- * @builtin CallbackSourceProbeSucceeded
- * @short Register callback function
- * @param string func Name of the callback handler function. Required callback prototype is <code>void(string url, string type)</code>. The callback function is evaluated when the probed source has type <code>type</code>.
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackSourceProbeSucceeded( const YCPString& func)
-{
- return SET_YCP_CB( CB_SourceProbeSucceeded, func );
-}
-
-/**
- * @builtin CallbackSourceProbeEnd
- * @short Register callback function
- * @param string func Name of the callback handler function. Required callback prototype is <code>void(string url, string error, string reason)</code>. The callback function is evaluated when source probing has been finished.
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackSourceProbeEnd( const YCPString& func)
-{
- return SET_YCP_CB( CB_SourceProbeEnd, func );
-}
-
-/**
- * @builtin CallbackSourceProbeProgress
- * @short Register callback function
- * @param string func Name of the callback handler function. Required callback prototype is <code>boolean(integer value)</code>. If the handler returns false the refresh is aborted.
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackSourceProbeProgress( const YCPString& func)
-{
- return SET_YCP_CB( CB_SourceProbeProgress, func );
-}
-
-/**
- * @builtin CallbackSourceProbeError
- * @short Register callback function
- * @param string func Name of the callback handler function. Required callback prototype is <code>string(string url, string error, string reason)</code>. The callback function is evaluated when an error occurrs. The callback function must return string "ABORT" or "RETRY".
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackSourceProbeError( const YCPString& func)
-{
- return SET_YCP_CB( CB_SourceProbeError, func );
-}
-
-
-YCPValue PkgModuleFunctions::CallbackSourceReportInit( const YCPString& func)
-{
- return SET_YCP_CB( CB_SourceReportInit, func );
-}
-
-YCPValue PkgModuleFunctions::CallbackSourceReportDestroy( const YCPString& func)
-{
- return SET_YCP_CB( CB_SourceReportDestroy, func );
-}
-
-YCPValue PkgModuleFunctions::CallbackSourceCreateInit( const YCPString& func)
-{
- return SET_YCP_CB( CB_SourceCreateInit, func );
-}
-
-YCPValue PkgModuleFunctions::CallbackSourceCreateDestroy( const YCPString& func)
-{
- return SET_YCP_CB( CB_SourceCreateDestroy, func );
-}
-
-/**
- * @builtin CallbackSourceProbeStart
- * @short Register callback function
- * @param string func Name of the callback handler function. Required callback prototype is <code>void(integer source_id, string url, string task)</code>.
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackSourceReportStart( const YCPString& func)
-{
- return SET_YCP_CB( CB_SourceReportStart, func );
-}
-
-/**
- * @builtin CallbackSourceReportProgress
- * @short Register callback function
- * @param string func Name of the callback handler function. Required callback prototype is <code>boolean(integer value)</code>. If the handler returns false the task is aborted.
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackSourceReportProgress( const YCPString& func)
-{
- return SET_YCP_CB( CB_SourceReportProgress, func );
-}
-
-/**
- * @builtin CallbackSourceReportError
- * @short Register callback function
- * @param string func Name of the callback handler function. Required callback prototype is <code>string(integer numeric_id, string url, string error, string reason)</code>. Parameter error is "NO_ERROR", "NOT_FOUND", "IO" or "INVALID". The callback function is evaluated when an error occurrs. The callback function must return string "ABORT", "IGNORE" or "RETRY".
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackSourceReportError( const YCPString& func)
-{
- return SET_YCP_CB( CB_SourceReportError, func );
-}
-
-/**
- * @builtin CallbackSourceReportEnd
- * @short Register callback function
- * @param string func Name of the callback handler function. Required callback prototype is <code>void(integer numeric_id, string url, string task, string error, string reason)</code>. Parameter error is "NO_ERROR", "NOT_FOUND", "IO" or "INVALID". The callback function is evaluated when an error occurrs. The callback function must return string "ABORT", "IGNORE" or "RETRY".
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackSourceReportEnd( const YCPString& func)
-{
- return SET_YCP_CB( CB_SourceReportEnd, func );
-}
-
-
-YCPValue PkgModuleFunctions::CallbackStartDownload( const YCPString& args ) {
- return SET_YCP_CB( CB_StartDownload, args );
-}
-YCPValue PkgModuleFunctions::CallbackProgressDownload( const YCPString& args ) {
- return SET_YCP_CB( CB_ProgressDownload, args );
-}
-YCPValue PkgModuleFunctions::CallbackDoneDownload( const YCPString& args ) {
- return SET_YCP_CB( CB_DoneDownload, args );
-}
-
-
-/**
- * @builtin CallbackScriptStart
- * @short Register callback function
- * @param string func Name of the callback handler function. Required callback prototype is <code>void(string patch_name, string patch_version, string patch_arch, string script_path, boolean installation)</code>. Parameter 'installation' is true when the script is called during installation of a patch, false means patch removal. The callback function is evaluated when a script (which is part of a patch) has been started.
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackScriptStart( const YCPString& args ) {
- return SET_YCP_CB( CB_ScriptStart, args );
-}
-/**
- * @builtin CallbackScriptProgress
- * @short Register callback function
- * @param string func Name of the callback handler function. Required callback prototype is <code>void(boolean ping, string output)</code>. If parameter 'ping' is true than there is no output available, but the script is still running (This functionality enables aborting the script). If it is false, 'output' contains (part of) the script output. The callback function is evaluated when a script is running.
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackScriptProgress( const YCPString& args ) {
- return SET_YCP_CB( CB_ScriptProgress, args );
-}
-/**
- * @builtin CallbackScriptProblem
- * @short Register callback function
- * @param string func Name of the callback handler function. Required callback prototype is <code>void(string description)</code>. The callback function is evaluated when an error occurrs.
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackScriptProblem( const YCPString& args ) {
- return SET_YCP_CB( CB_ScriptProblem, args );
-}
-/**
- * @builtin CallbackScriptFinish
- * @short Register callback function
- * @param string func Name of the callback handler function. Required callback prototype is <code>void()</code>. The callback function is evaluated when the script has been finished.
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackScriptFinish( const YCPString& args ) {
- return SET_YCP_CB( CB_ScriptFinish, args );
-}
-/**
- * @builtin CallbackMessage
- * @short Register callback function
- * @param string func Name of the callback handler function. Required callback prototype is <code>void(string patch_name, string patch_version, string patch_arch, string message)</code>. The callback function is evaluated when a message which is part of a patch should be displayed.
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackMessage( const YCPString& args ) {
- return SET_YCP_CB( CB_Message, args );
-}
-
-/**
- * @builtin CallbackAuthentication
- * @short Register callback function
- * @param string func Name of the callback handler function. Required callback prototype is <code>map(string url, string message, string username, string password)</code>. The returned map must contain these items: $[ "username" : string, "password" : string, "continue" : boolean ]. If <code>"continue"</code> value is false or is missing the authentification (and the download process) is canceled. The callback function is evaluated when user authentication is required to download the requested file.
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackAuthentication( const YCPString& func ) {
- return SET_YCP_CB( CB_Authentication, func );
-}
-
-/**
- * @builtin CallbackProgressReportStart
- * @short Register a callback function
- * @param string func Name of the callback handler function. Required callback prototype is <code>void(integer id, string task, boolean in_percent, boolean is_alive, integer min, integer max, integer val_raw, integer val_percent)</code>. Parameter id is used for callback identification in the Progress() and in the End() callbacks, task describe the action. Parameter in_percent defines whether the progress will be reported in percent, if is_alive is true then the progress will be 'still alive' tick, if both in_percent and is_alive are then a raw value is reported (e.g. number of processed files without knowing the total number).
- * The callback function is evaluated when an progress event starts
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackProgressReportStart(const YCPString& func)
-{
- return SET_YCP_CB( CB_ProgressStart, func );
-}
-
-/**
- * @builtin CallbackProgressReportProgress
- * @short Register a callback function
- * @param string func Name of the callback handler function. Required callback prototype is <code>boolean(integer id, integer val_raw, integer val_percent)</code>. Parameter id identifies the callback, val_raw is raw status, val_percent is in percent or if the total progress is not known it's -1 (the callback is a 'tick' in this case). If the handler returns false the task is aborted.
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackProgressReportProgress(const YCPString& func)
-{
- return SET_YCP_CB( CB_ProgressProgress, func );
-}
-
-/**
- * @builtin CallbackProgressReportEnd
- * @short Register a callback function
- * @param string func Name of the callback handler function. Required callback prototype is <code>void(integer id)</code>. The id identifies the callback.
- * The callback function is evaluated when an progress event finishes
- * @return void
- */
-YCPValue PkgModuleFunctions::CallbackProgressReportEnd(const YCPString& func)
-{
- return SET_YCP_CB( CB_ProgressDone, func );
-}
-
-YCPValue PkgModuleFunctions::CallbackInitDownload( const YCPString& args ) {
- return SET_YCP_CB( CB_InitDownload, args );
-}
-
-YCPValue PkgModuleFunctions::CallbackDestDownload( const YCPString& args ) {
- return SET_YCP_CB( CB_DestDownload, args );
-}
-
-YCPValue PkgModuleFunctions::CallbackProcessStart( const YCPString& func )
-{
- return SET_YCP_CB( CB_ProcessStart, func );
-}
-
-YCPValue PkgModuleFunctions::CallbackProcessNextStage( const YCPString& func )
-{
- return SET_YCP_CB( CB_ProcessNextStage, func );
-}
-
-YCPValue PkgModuleFunctions::CallbackProcessDone( const YCPString& func )
-{
- return SET_YCP_CB( CB_ProcessFinished, func );
-}
-
-YCPValue PkgModuleFunctions::CallbackProcessProgress( const YCPString& func )
-{
- return SET_YCP_CB( CB_ProcessProgress, func);
-}
-
-#undef SET_YCP_CB
Copied: trunk/pkg-bindings/src/Callbacks_Register.cc (from r42663, trunk/pkg-bindings/src/Callbacks.cc)
URL: http://svn.opensuse.org/viewcvs/yast/trunk/pkg-bindings/src/Callbacks_Regis…
==============================================================================
--- trunk/pkg-bindings/src/Callbacks.cc (original)
+++ trunk/pkg-bindings/src/Callbacks_Register.cc Thu Dec 6 07:56:58 2007
@@ -1,1879 +1,33 @@
-/*---------------------------------------------------------------------\
-| |
-| __ __ ____ _____ ____ |
-| \ \ / /_ _/ ___|_ _|___ \ |
-| \ V / _` \___ \ | | __) | |
-| | | (_| |___) || | / __/ |
-| |_|\__,_|____/ |_| |_____| |
-| |
-| core system |
-| (C) SuSE GmbH |
-\----------------------------------------------------------------------/
-
- File: PkgModuleCallbacks.cc
-
- Author: Klaus Kaempf <kkaempf(a)suse.de>
- Maintainer: Klaus Kaempf <kkaempf(a)suse.de>
- Summary: Register Package Manager callbacks
- Namespace: Pkg
-
- Purpose: Implement callbacks from ZYpp to UI/WFM.
-
-/-*/
-
-#include <iostream>
+/* ------------------------------------------------------------------------------
+ * Copyright (c) 2007 Novell, Inc. All Rights Reserved.
+ *
+ *
+ * This program is free software; you can redistribute it and/or modify it under
+ * the terms of version 2 of the GNU General Public License as published by the
+ * Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+ * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along with
+ * this program; if not, contact Novell, Inc.
+ *
+ * To contact Novell about this file by physical or electronic mail, you may find
+ * current contact information at www.novell.com.
+ * ------------------------------------------------------------------------------
+ */
-#include <y2util/stringutil.h>
+/*
+ File: $Id:$
+ Author: Ladislav Slezák <lslezak(a)novell.com>
+ Summary: Functions for registering YCP callbacks from Yast
+*/
#include "PkgModuleFunctions.h"
#include "Callbacks.h"
#include "Callbacks.YCP.h" // PkgModuleFunctions::CallbackHandler::YCPCallbacks
-#include <zypp/ZYppCallbacks.h>
-#include <zypp/Package.h>
-#include <zypp/Product.h>
-#include <zypp/KeyRing.h>
-#include <zypp/PublicKey.h>
-#include <zypp/Digest.h>
-
-// FIXME: do this nicer, source create use this to avoid user feedback
-// on probing of source type
-
-ZyppRecipients::MediaChangeSensitivity _silent_probing = ZyppRecipients::MEDIA_CHANGE_FULL;
-
-// remember redirected URLs
-// FIXME huh?
-
-typedef std::map<unsigned, zypp::Url> MediaMap;
-typedef std::map<zypp::Url, MediaMap> RedirectMap;
-
-RedirectMap redirect_map;
-
-///////////////////////////////////////////////////////////////////
-namespace ZyppRecipients {
-///////////////////////////////////////////////////////////////////
-
- typedef PkgModuleFunctions::CallbackHandler::YCPCallbacks YCPCallbacks;
-
- ///////////////////////////////////////////////////////////////////
- // Data excange. Shared between Recipients, inherited by ZyppReceive.
- ///////////////////////////////////////////////////////////////////
- struct RecipientCtl {
- const YCPCallbacks & _ycpcb;
- public:
- RecipientCtl( const YCPCallbacks & ycpcb_r )
- : _ycpcb( ycpcb_r )
- {}
- virtual ~RecipientCtl() {}
- };
-
- ///////////////////////////////////////////////////////////////////
- // Base class common to Recipients. Provides RecipientCtl and inherits
- // YCPCallbacks::Send(see comment in PkgModuleCallbacks.YCP.h).
- ///////////////////////////////////////////////////////////////////
- struct Recipient : public YCPCallbacks::Send {
- RecipientCtl & _control; // shared beween Recipients.
- public:
- Recipient( RecipientCtl & control_r )
- : Send( control_r._ycpcb )
- , _control( control_r )
- {}
- virtual ~Recipient() {}
- };
-
-
- ///////////////////////////////////////////////////////////////////
- // ConvertDbCallback
- ///////////////////////////////////////////////////////////////////
- struct ConvertDbReceive : public Recipient, public zypp::callback::ReceiveReport<zypp::target::rpm::ConvertDBReport>
- {
- ConvertDbReceive( RecipientCtl & construct_r ) : Recipient( construct_r ) {}
-
- virtual void reportbegin()
- {
- y2milestone("Convert DB Init Callback");
- }
-
- virtual void reportend()
- {
- y2milestone("Convert DB Destroy Callback");
- }
-
- virtual void start(zypp::Pathname pname) {
- CB callback(ycpcb(YCPCallbacks::CB_StartConvertDb));
- if (callback._set) {
- callback.addStr(pname.asString());
- callback.evaluate();
- }
- }
-
- virtual bool progress(int value, zypp::Pathname pth)
- {
- CB callback( ycpcb( YCPCallbacks::CB_ProgressConvertDb ) );
- if (callback._set) {
- callback.addInt( value );
- // TODO adapt callback typeinfo to zypp
- callback.addInt( 100 );
- callback.addInt( 0 /*failed*/ );
- callback.addInt( 0 /* ignored */ );
- callback.addInt( 1 /*alreadyInV4*/ );
- callback.evaluate();
- }
-
- // return default value from the parent class
- return zypp::target::rpm::ConvertDBReport::progress(value, pth);
- }
-
- virtual void finish(zypp::Pathname path, zypp::target::rpm::ConvertDBReport::Error error, const std::string &reason)
- {
- CB callback( ycpcb( YCPCallbacks::CB_StopConvertDb ) );
- if (callback._set) {
- callback.addInt( error );
- callback.addStr( reason );
- callback.evaluateStr(); // return value ignored by RpmDb
- }
- }
- };
-
-
-
- ///////////////////////////////////////////////////////////////////
- // RebuildDbCallback
- ///////////////////////////////////////////////////////////////////
- struct RebuildDbReceive : public Recipient, public zypp::callback::ReceiveReport<zypp::target::rpm::RebuildDBReport>
- {
- RebuildDbReceive( RecipientCtl & construct_r ) : Recipient( construct_r ) {}
-
- virtual void reportbegin()
- {
- }
-
- virtual void reportend()
- {
- }
-
- virtual void start(zypp::Pathname path)
- {
- CB callback( ycpcb( YCPCallbacks::CB_StartRebuildDb ) );
- if ( callback._set ) {
- callback.evaluate();
- }
- }
-
- virtual bool progress(int value, zypp::Pathname pth)
- {
- CB callback( ycpcb( YCPCallbacks::CB_ProgressRebuildDb ) );
- if ( callback._set ) {
- // report changed values
- callback.addInt( value );
- callback.evaluate();
- }
-
- // return default value from the parent class
- return zypp::target::rpm::RebuildDBReport::progress(value, pth);
- }
-
- virtual void finish(zypp::Pathname path, zypp::target::rpm::RebuildDBReport::Error error, const std::string &reason)
- {
- CB callback( ycpcb( YCPCallbacks::CB_StopRebuildDb ) );
- if (callback._set) {
- callback.addInt( error );
- callback.addStr( reason );
- callback.evaluateStr(); // return value ignored by RpmDb
- }
- }
- };
-
- struct ScanDbReceive : public Recipient, public zypp::callback::ReceiveReport<zypp::target::rpm::ScanDBReport>
- {
- ScanDbReceive( RecipientCtl & construct_r ) : Recipient( construct_r ) {}
-
- virtual void start()
- {
- CB callback( ycpcb( YCPCallbacks::CB_StartScanDb ) );
- if ( callback._set ) {
- callback.evaluate();
- }
- }
-
- virtual bool progress(int value)
- {
- CB callback( ycpcb( YCPCallbacks::CB_ProgressScanDb ) );
- if ( callback._set ) {
- // report changed values
- callback.addInt( value );
- return callback.evaluateBool();
- }
-
- // return default value from the parent class
- return zypp::target::rpm::ScanDBReport::progress(value);
- }
-
- virtual Action problem(zypp::target::rpm::ScanDBReport::Error error, const std::string &description)
- {
- CB callback( ycpcb( YCPCallbacks::CB_ErrorScanDb ) );
- if ( callback._set ) {
- callback.addInt( error );
- callback.addStr( description );
-
- std::string ret = callback.evaluateStr();
-
- // "C" = cancel (abort)
- if (ret == "C") return zypp::target::rpm::ScanDBReport::ABORT;
-
- // "R" = retry
- if (ret == "R") return zypp::target::rpm::ScanDBReport::RETRY;
-
- // "I" = ignore
- if (ret == "I") return zypp::target::rpm::ScanDBReport::IGNORE;
-
- y2warning("Unknown callback result '%s', using default value", ret.c_str());
- }
-
- return zypp::target::rpm::ScanDBReport::problem(error, description);
- }
-
- virtual void finish(zypp::target::rpm::ScanDBReport::Error error, const std::string &reason)
- {
- CB callback( ycpcb( YCPCallbacks::CB_DoneScanDb ) );
- if ( callback._set ) {
- callback.addInt( error );
- callback.addStr( reason );
-
- callback.evaluate();
- }
- }
- };
-
- ///////////////////////////////////////////////////////////////////
- // InstallPkgCallback
- ///////////////////////////////////////////////////////////////////
- struct InstallPkgReceive : public Recipient, public zypp::callback::ReceiveReport<zypp::target::rpm::InstallResolvableReport>
- {
- zypp::Resolvable::constPtr _last;
- int last_reported;
-
- InstallPkgReceive(RecipientCtl & construct_r) : Recipient(construct_r)
- {
- }
-
- virtual void reportbegin()
- {
- }
-
- virtual void reportend()
- {
- }
-
- virtual void start(zypp::Resolvable::constPtr resolvable)
- {
- // initialize the counter
- last_reported = 0;
-
-#warning install non-package
- zypp::Package::constPtr res =
- zypp::asKind<zypp::Package>(resolvable);
-
- // if we have started this resolvable already, don't do it again
- if( _last == resolvable )
- return;
-
- CB callback( ycpcb( YCPCallbacks::CB_StartPackage ) );
- if (callback._set) {
- callback.addStr(res->location().filename());
- callback.addStr(res->summary());
- callback.addInt(res->size());
- callback.addBool(false); // is_delete = false (package installation)
- callback.evaluateBool();
- }
-
- _last = resolvable;
- }
-
- virtual bool progress(int value, zypp::Resolvable::constPtr resolvable)
- {
- CB callback( ycpcb( YCPCallbacks::CB_ProgressPackage) );
- // call the callback function only if the difference since the last call is at least 5%
- // or if 100% is reached
- if (callback._set && (value - last_reported >= 5 || last_reported - value >= 5 || value == 100))
- {
- callback.addInt( value );
- bool res = callback.evaluateBool();
-
- if( !res )
- y2milestone( "Package installation callback returned abort" );
-
- last_reported = value;
- return res;
- }
-
- // return default value from the parent class
- return zypp::target::rpm::InstallResolvableReport::progress(value, resolvable);
- }
-
- virtual Action problem(
- zypp::Resolvable::constPtr resolvable
- , zypp::target::rpm::InstallResolvableReport::Error error
- , const std::string &description
- , zypp::target::rpm::InstallResolvableReport::RpmLevel level
- )
- {
- if (level != zypp::target::rpm::InstallResolvableReport::RPM_NODEPS_FORCE)
- {
- y2milestone( "Retrying installation problem with too low severity (%d)", level);
- return zypp::target::rpm::InstallResolvableReport::ABORT;
- }
-
- _last = zypp::Resolvable::constPtr();
-
- CB callback( ycpcb( YCPCallbacks::CB_DonePackage) );
- if (callback._set) {
- callback.addInt( error );
- callback.addStr( description );
-
- std::string ret = callback.evaluateStr();
-
- // "R" = retry
- if (ret == "R") return zypp::target::rpm::InstallResolvableReport::RETRY;
-
- // "C" = cancel
- if (ret == "C") return zypp::target::rpm::InstallResolvableReport::ABORT;
-
- // otherwise ignore
- return zypp::target::rpm::InstallResolvableReport::IGNORE;
- }
-
- return zypp::target::rpm::InstallResolvableReport::problem
- (resolvable, error, description, level);
- }
-
- virtual void finish(zypp::Resolvable::constPtr resolvable, Error error, const std::string &reason, zypp::target::rpm::InstallResolvableReport::RpmLevel level)
- {
- if (error != zypp::target::rpm::InstallResolvableReport::NO_ERROR && level != zypp::target::rpm::InstallResolvableReport::RPM_NODEPS_FORCE)
- {
- y2milestone( "Skipping finish due to retrying installation problem with too low severity (%d)", level);
- return;
- }
-
- CB callback( ycpcb( YCPCallbacks::CB_DonePackage) );
- if (callback._set) {
- callback.addInt( level == zypp::target::rpm::InstallResolvableReport::RPM_NODEPS_FORCE ? error : NO_ERROR);
- callback.addStr( reason );
- callback.evaluateStr(); // return value ignored by RpmDb
- }
- }
- };
-
-
- ///////////////////////////////////////////////////////////////////
- // RemovePkgCallback
- ///////////////////////////////////////////////////////////////////
- struct RemovePkgReceive : public Recipient, public zypp::callback::ReceiveReport<zypp::target::rpm::RemoveResolvableReport>
- {
- RemovePkgReceive( RecipientCtl & construct_r ) : Recipient( construct_r ) {}
-
- virtual void reportbegin()
- {
- }
-
- virtual void reportend()
- {
- }
-
- virtual void start(zypp::Resolvable::constPtr resolvable)
- {
- CB callback( ycpcb( YCPCallbacks::CB_StartPackage ) );
- if (callback._set) {
- callback.addStr(resolvable->name());
- callback.addStr(std::string());
- callback.addInt(-1);
- callback.addBool(true); // is_delete = true
- callback.evaluateBool();
- }
- }
-
- virtual bool progress(int value, zypp::Resolvable::constPtr resolvable)
- {
- CB callback( ycpcb( YCPCallbacks::CB_ProgressPackage) );
- if (callback._set) {
- callback.addInt( value );
-
- bool res = callback.evaluateBool();
-
- if( !res )
- {
- y2milestone( "Package remove callback returned abort" );
- }
-
- return res;
- }
-
- // return default value from the parent class
- return zypp::target::rpm::RemoveResolvableReport::progress(value, resolvable);
- }
-
- virtual void finish(zypp::Resolvable::constPtr resolvable, zypp::target::rpm::RemoveResolvableReport::Error error, const std::string &reason)
- {
- CB callback( ycpcb( YCPCallbacks::CB_DonePackage) );
- if (callback._set) {
- callback.addInt( error );
- callback.addStr( reason );
- callback.evaluateStr(); // return value ignored by RpmDb
- }
- }
- };
-
-
- struct ProgressReceive : public Recipient, public zypp::callback::ReceiveReport<zypp::ProgressReport>
- {
- ProgressReceive( RecipientCtl & construct_r ) : Recipient( construct_r ) {}
-
- virtual void start(const zypp::ProgressData &task)
- {
- CB callback( ycpcb( YCPCallbacks::CB_ProgressStart ) );
- // TODO: change it to y2debug later
- y2milestone("ProgressStart: id:%d, %s", task.numericId(), task.name().c_str());
-
- if (callback._set)
- {
- callback.addInt( task.numericId() );
- callback.addStr( task.name() );
- callback.addBool( task.reportPercent() );
- callback.addBool( task.reportAlive() );
- callback.addInt( task.min() );
- callback.addInt( task.max() );
- callback.addInt( task.val() );
- callback.addInt( task.reportValue() );
- callback.evaluate();
- }
- }
-
- virtual bool progress(const zypp::ProgressData &task)
- {
- CB callback( ycpcb( YCPCallbacks::CB_ProgressProgress ) );
- // TODO: change it to y2debug later
- y2milestone("ProgressProgress: id:%d, %s: %lld%%", task.numericId(), task.name().c_str(), task.reportValue());
-
- if (callback._set)
- {
- callback.addInt( task.numericId() );
- callback.addInt( task.val() );
- callback.addInt( task.reportValue() );
- return callback.evaluateBool();
- }
-
- return zypp::ProgressReport::progress(task);
- }
-
- virtual void finish( const zypp::ProgressData &task )
- {
- CB callback( ycpcb( YCPCallbacks::CB_ProgressDone ) );
- // TODO: change it to y2debug later
- y2milestone("ProgressFinish: id:%d, %s", task.numericId(), task.name().c_str());
-
- if (callback._set)
- {
- callback.addInt( task.numericId() );
- callback.evaluate();
- }
- }
- };
-
-
-
- ///////////////////////////////////////////////////////////////////
- // DownloadResolvableCallback
- ///////////////////////////////////////////////////////////////////
- struct DownloadResolvableReceive : public Recipient, public zypp::callback::ReceiveReport<zypp::repo::DownloadResolvableReport>
- {
- static int last_source_id;
- static int last_source_media;
- const PkgModuleFunctions &_pkg_ref;
-
- DownloadResolvableReceive( RecipientCtl & construct_r, const PkgModuleFunctions &pk ) : Recipient( construct_r ), _pkg_ref(pk) {}
- int last_reported;
- int last_reported_delta_download;
- int last_reported_delta_apply;
- int last_reported_patch_download;
-
- virtual void reportbegin()
- {
- }
-
- virtual void reportend()
- {
- }
-
- virtual void start( zypp::Resolvable::constPtr resolvable_ptr, const zypp::Url &url)
- {
- unsigned size = 0;
- last_reported = 0;
-
- if ( zypp::isKind<zypp::Package> (resolvable_ptr) )
- {
- zypp::Package::constPtr pkg =
- zypp::asKind<zypp::Package>(resolvable_ptr);
-
- size = pkg->downloadSize();
-
- // convert the repo ID
- long long source_id = _pkg_ref.logFindAlias(pkg->repository().info().alias());
- int media_nr = pkg->mediaNr();
-
- if( source_id != last_source_id || media_nr != last_source_media )
- {
- CB callback( ycpcb( YCPCallbacks::CB_SourceChange ) );
- if (callback._set) {
- callback.addInt( source_id );
- callback.addInt( media_nr );
- callback.evaluate();
- }
- last_source_id = source_id;
- last_source_media = media_nr;
- }
- }
-
- CB callback( ycpcb( YCPCallbacks::CB_StartProvide ) );
- if (callback._set) {
- bool remote = url.getScheme() != "cd" && url.getScheme() != "dvd"
- && url.getScheme() != "nfs";
- callback.addStr(resolvable_ptr->name());
- callback.addInt( size );
- callback.addBool(remote);
- callback.evaluateBool();
- }
- }
-
- virtual void finish(zypp::Resolvable::constPtr resolvable, zypp::repo::DownloadResolvableReport::Error error, const std::string &reason)
- {
- CB callback( ycpcb( YCPCallbacks::CB_DoneProvide) );
- if (callback._set) {
- callback.addInt( error );
- callback.addStr( reason );
- callback.addStr( resolvable->name() );
- callback.evaluateStr(); // return value is ignored
- }
- }
-
- virtual bool progress(int value, zypp::Resolvable::constPtr resolvable_ptr)
- {
- CB callback( ycpcb( YCPCallbacks::CB_ProgressProvide) );
- if (callback._set && (value - last_reported >= 5 || last_reported - value >= 5 || value == 100))
- {
- last_reported = value;
- callback.addInt( value );
- return callback.evaluateBool(); // return value ignored by RpmDb
- }
-
- return zypp::repo::DownloadResolvableReport::progress(value, resolvable_ptr);
- }
-
- virtual Action problem(zypp::Resolvable::constPtr resolvable_ptr, zypp::repo::DownloadResolvableReport::Error error, const std::string &description)
- {
- CB callback( ycpcb( YCPCallbacks::CB_DoneProvide) );
- if (callback._set) {
- callback.addInt( error );
- callback.addStr( description );
- callback.addStr( resolvable_ptr->name() );
- std::string ret = callback.evaluateStr();
-
- // "R" = retry
- if (ret == "R") return zypp::repo::DownloadResolvableReport::RETRY;
-
- // "C" = cancel
- if (ret == "C") return zypp::repo::DownloadResolvableReport::ABORT;
-
- // "I" = ignore
- if (ret == "I") return zypp::repo::DownloadResolvableReport::IGNORE;
-
- // otherwise return the default value from the parent class
- }
-
- // return the default value from the parent class
- return zypp::repo::DownloadResolvableReport::problem(resolvable_ptr, error, description);
- }
-
- // Download delta rpm:
- // - path below url reported on start()
- // - expected download size (0 if unknown)
- // - download is interruptable
- // - problems are just informative
- virtual void startDeltaDownload( const zypp::Pathname & filename, const zypp::ByteCount & downloadsize )
- {
- // reset the counter
- last_reported_delta_download = 0;
-
- CB callback( ycpcb( YCPCallbacks::CB_StartDeltaDownload) );
- if (callback._set) {
- callback.addStr( filename.asString() );
- callback.addInt( downloadsize );
-
- callback.evaluate();
- }
- }
-
- virtual bool progressDeltaDownload( int value )
- {
- CB callback( ycpcb( YCPCallbacks::CB_ProgressDeltaDownload) );
- if (callback._set && (value - last_reported_delta_download >= 5 || last_reported_delta_download - value >= 5 || value == 100))
- {
- last_reported_delta_download = value;
- callback.addInt( value );
-
- return callback.evaluateBool();
- }
-
- return zypp::repo::DownloadResolvableReport::progressDeltaDownload(value);
- }
-
- virtual void problemDeltaDownload( const std::string &description )
- {
- CB callback( ycpcb( YCPCallbacks::CB_ProblemDeltaDownload ) );
- if (callback._set) {
- callback.addStr( description );
-
- callback.evaluate();
- }
- }
-
- virtual void finishDeltaDownload()
- {
- CB callback( ycpcb( YCPCallbacks::CB_FinishDeltaDownload ) );
-
- if (callback._set)
- {
- callback.evaluate();
- }
- }
-
-
- // Apply delta rpm:
- // - local path of downloaded delta
- // - apply is not interruptable
- // - problems are just informative
- virtual void startDeltaApply( const zypp::Pathname & filename )
- {
- // reset the counter
- last_reported_delta_apply = 0;
-
- CB callback( ycpcb( YCPCallbacks::CB_StartDeltaApply) );
- if (callback._set) {
- callback.addStr( filename.asString() );
-
- callback.evaluate();
- }
- }
-
- virtual void progressDeltaApply( int value )
- {
- CB callback( ycpcb( YCPCallbacks::CB_ProgressDeltaApply ) );
- if (callback._set && (value - last_reported_delta_apply >= 5 || last_reported_delta_apply - value >= 5 || value == 100))
- {
- last_reported_delta_apply = value;
- callback.addInt( value );
-
- callback.evaluate();
- }
- }
-
- virtual void problemDeltaApply( const std::string &description )
- {
- CB callback( ycpcb( YCPCallbacks::CB_ProblemDeltaApply ) );
-
- if (callback._set) {
- callback.addStr( description );
-
- callback.evaluate();
- }
- }
-
- virtual void finishDeltaApply()
- {
- CB callback( ycpcb( YCPCallbacks::CB_FinishDeltaApply ) );
-
- if (callback._set)
- {
- callback.evaluate();
- }
- }
-
-
- // Download patch rpm:
- // - path below url reported on start()
- // - expected download size (0 if unknown)
- // - download is interruptable
- virtual void startPatchDownload( const zypp::Pathname & filename, const zypp::ByteCount & downloadsize )
- {
- // reset the counter
- last_reported_patch_download = 0;
-
- CB callback( ycpcb( YCPCallbacks::CB_StartPatchDownload ) );
- if (callback._set) {
- callback.addStr( filename.asString() );
- callback.addInt( downloadsize );
-
- callback.evaluate();
- }
- }
-
- virtual bool progressPatchDownload( int value )
- {
- CB callback( ycpcb( YCPCallbacks::CB_ProgressPatchDownload) );
- if (callback._set && (value - last_reported_patch_download >= 5 || last_reported_patch_download - value >= 5 || value == 100))
- {
- last_reported_patch_download = value;
- callback.addInt( value );
-
- return callback.evaluateBool();
- }
-
- return zypp::repo::DownloadResolvableReport::progressPatchDownload(value);
- }
-
- virtual void problemPatchDownload( const std::string &description )
- {
- CB callback( ycpcb( YCPCallbacks::CB_ProblemPatchDownload ) );
-
- if (callback._set) {
- callback.addStr( description );
-
- callback.evaluate();
- }
- }
-
- virtual void finishPatchDownload()
- {
- CB callback( ycpcb( YCPCallbacks::CB_FinishPatchDownload ) );
-
- if (callback._set)
- {
- callback.evaluate();
- }
- }
-
- };
-
- int DownloadResolvableReceive::last_source_id = -1;
- int DownloadResolvableReceive::last_source_media = -1;
-
-
- ///////////////////////////////////////////////////////////////////
- // DownloadProgressReceive
- ///////////////////////////////////////////////////////////////////
- struct DownloadProgressReceive : public Recipient, public zypp::callback::ReceiveReport<zypp::media::DownloadProgressReport>
- {
- int last_reported;
-
- DownloadProgressReceive( RecipientCtl & construct_r ) : Recipient( construct_r ) {}
-
- virtual void start( const zypp::Url &file, zypp::Pathname localfile )
- {
- last_reported = 0;
- CB callback( ycpcb( YCPCallbacks::CB_StartDownload ) );
-
- if ( callback._set )
- {
- callback.addStr( file.asString() );
- callback.addStr( localfile.asString() );
- callback.evaluate();
- }
- }
-
- virtual bool progress(int value, const zypp::Url &file)
- {
- CB callback( ycpcb( YCPCallbacks::CB_ProgressDownload ) );
- // call the callback function only if the difference since the last call is at least 5%
- // or if 100% is reached
- if (callback._set && (value - last_reported >= 5 || last_reported - value >= 5 || value == 100))
- {
- last_reported = value;
- // report changed values
- callback.addInt( value );
- callback.addInt( 100 );
- return callback.evaluateBool( true ); // default == continue
- }
-
- return zypp::media::DownloadProgressReport::progress(value, file);
- }
-
- virtual Action problem( const zypp::Url &file, zypp::media::DownloadProgressReport::Error error, const std::string &description)
- {
- CB callback( ycpcb( YCPCallbacks::CB_DoneProvide) );
-
- if (callback._set) {
- callback.addInt( error );
- callback.addStr( description );
- callback.addStr( file.asString() ); // FIXME: on error name, for OK, local path
- std::string ret = callback.evaluateStr();
-
- y2milestone("DoneProvide result: %s", ret.c_str());
-
- // "R" = retry
- if (ret == "R") return zypp::media::DownloadProgressReport::RETRY;
-
- // "C" = cancel
- if (ret == "C") return zypp::media::DownloadProgressReport::ABORT;
-
- // "I" = cancel
- if (ret == "I") return zypp::media::DownloadProgressReport::IGNORE;
-
- // otherwise return the default value from the parent class
- }
- return zypp::media::DownloadProgressReport::problem(file, error, description);
- }
-
- virtual void finish( const zypp::Url &file, zypp::media::DownloadProgressReport::Error error, const std::string &reason)
- {
- CB callback( ycpcb( YCPCallbacks::CB_DoneDownload ) );
-
- zypp::media::DownloadProgressReport::Error err = error;
-
- // ignore errors for optional files
- if ( _silent_probing == MEDIA_CHANGE_DISABLE ||
- _silent_probing == MEDIA_CHANGE_OPTIONALFILE)
- {
- err = zypp::media::DownloadProgressReport::NO_ERROR;
- }
-
- if ( callback._set ) {
- callback.addInt( err );
- callback.addStr( reason );
- callback.evaluate();
- }
- }
- };
-
-
- ///////////////////////////////////////////////////////////////////
- // ScriptExecCallbacks
- ///////////////////////////////////////////////////////////////////
- struct ScriptExecReceive : public Recipient, public zypp::callback::ReceiveReport<zypp::target::ScriptResolvableReport>
- {
- ScriptExecReceive( RecipientCtl & construct_r ) : Recipient( construct_r ) {}
-
- virtual void start( const zypp::Resolvable::constPtr &script_r, const zypp::Pathname &path_r, zypp::target::ScriptResolvableReport::Task task)
- {
- CB callback( ycpcb( YCPCallbacks::CB_ScriptStart) );
- if ( callback._set )
- {
- callback.addStr(script_r->name());
- callback.addStr(script_r->edition().asString());
- callback.addStr(script_r->arch().asString());
- callback.addStr(path_r);
- callback.addBool(task == zypp::target::ScriptResolvableReport::DO);
- callback.evaluate();
- }
- }
-
- virtual bool progress( zypp::target::ScriptResolvableReport::Notify ping, const std::string &out = std::string() )
- {
- CB callback( ycpcb( YCPCallbacks::CB_ScriptProgress) );
-
- if ( callback._set )
- {
- callback.addBool(ping == zypp::target::ScriptResolvableReport::PING);
- callback.addStr(out);
-
- // false = abort the script
- return callback.evaluateBool();
- }
- else
- {
- // return the default implementation
- return zypp::target::ScriptResolvableReport::progress(ping, out);
- }
- }
-
- virtual void problem( const std::string &description )
- {
- CB callback( ycpcb( YCPCallbacks::CB_ScriptProblem) );
-
- if ( callback._set )
- {
- callback.addStr(description);
- callback.evaluate();
- }
- }
-
- virtual void finish()
- {
- CB callback( ycpcb( YCPCallbacks::CB_ScriptFinish) );
-
- if ( callback._set )
- {
- callback.evaluate();
- }
- }
- };
-
- struct MessageReceive : public Recipient, public zypp::callback::ReceiveReport<zypp::target::MessageResolvableReport>
- {
- MessageReceive( RecipientCtl & construct_r ) : Recipient( construct_r ) {}
-
- virtual void show(zypp::Message::constPtr message)
- {
- CB callback( ycpcb( YCPCallbacks::CB_Message) );
-
- if ( callback._set )
- {
- zypp::Patch::constPtr p = message->patch();
-
- callback.addStr(p->name());
- callback.addStr(p->edition().asString());
- callback.addStr(p->arch().asString());
- callback.addStr(message->text().asString());
-
- callback.evaluate();
- }
- }
- };
-
- struct AuthReceive : public Recipient, public zypp::callback::ReceiveReport<zypp::media::AuthenticationReport>
- {
- AuthReceive( RecipientCtl & construct_r ) : Recipient( construct_r ) {}
-
- virtual bool prompt(const zypp::Url& url, const std::string& msg, zypp::media::AuthData& auth_data)
- {
- CB callback( ycpcb( YCPCallbacks::CB_Authentication ) );
-
- if (callback._set)
- {
- callback.addStr(url.asString());
- callback.addStr(msg);
- callback.addStr(auth_data.username());
- callback.addStr(auth_data.password());
-
- YCPMap cbk(callback.evaluateMap());
-
- YCPValue ycp_val = cbk->value(YCPString("username"));
- if (!ycp_val.isNull() && ycp_val->isString())
- {
- // set the entered username
- auth_data.setUserName(ycp_val->asString()->value());
- }
- else
- {
- y2error("Invalid/missing value 'username'");
- }
-
- ycp_val = cbk->value(YCPString("password"));
- if (!ycp_val.isNull() && ycp_val->isString())
- {
- // set the entered password
- auth_data.setPassword(ycp_val->asString()->value());
- }
- else
- {
- y2error("Invalid/missing value 'password'");
- }
-
- // authentication confirmed?
- bool ret = false;
-
- ycp_val = cbk->value(YCPString("continue"));
- if (!ycp_val.isNull() && ycp_val->isBoolean())
- {
- // continue?
- ret = ycp_val->asBoolean()->value();
- y2milestone("Use the authentication data: %s", ret ? "true" : "false");
- }
- else
- {
- y2error("Invalid/missing value 'continue'");
- }
-
- return ret;
- }
-
- // return the default value from the parent class
- return zypp::media::AuthenticationReport::prompt(url, msg, auth_data);
- }
- };
-
- ///////////////////////////////////////////////////////////////////
- // MediaChangeCallback
- ///////////////////////////////////////////////////////////////////
- struct MediaChangeReceive : public Recipient, public zypp::callback::ReceiveReport<zypp::media::MediaChangeReport>
- {
- MediaChangeReceive( RecipientCtl & construct_r ) : Recipient( construct_r ) {}
-
- virtual Action requestMedia(zypp::Url &url, unsigned int mediumNr, zypp::media::MediaChangeReport::Error error, const std::string &description)
- {
- if ( _silent_probing == MEDIA_CHANGE_DISABLE )
- return zypp::media::MediaChangeReport::ABORT;
-
- if ( _silent_probing == MEDIA_CHANGE_OPTIONALFILE
- && error == zypp::media::MediaChangeReport::NOT_FOUND )
- return zypp::media::MediaChangeReport::ABORT;
-
- CB callback( ycpcb( YCPCallbacks::CB_MediaChange ) );
- if ( callback._set )
- {
- // error message
- callback.addStr( description );
-
- // search URL in the redirection map
- RedirectMap::const_iterator source_it = redirect_map.find(url);
- bool found = false;
- zypp::Url report_url;
-
- if (source_it != redirect_map.end())
- {
- // search medium in the redirection map
- MediaMap::const_iterator media_it = (*source_it).second.find(mediumNr);
-
- if (media_it != (*source_it).second.end())
- {
- // found medium in the source map
- found = true;
- // report the redirected URL
- report_url = (*media_it).second;
-
- y2milestone("Using redirected URL %s, original URL: %s", report_url.asString().c_str(), url.asString().c_str());
- }
- }
-
- if (!found)
- {
- // the source has not been redirected
- // use URL of the source
- report_url = url;
- }
-
- // current URL
- callback.addStr( report_url.asString() );
-
- // current product name (use the alias, see #214886)
- callback.addStr( std::string() /*FIXME*/ );
-
- // current medium, -1 means enable [Ignore]
- callback.addInt( 0 );
-
- // current label, not used now
- callback.addStr( std::string() );
-
- // requested medium
- callback.addInt( mediumNr );
-
- // requested product, "" = use the current product
- callback.addStr( std::string() );
-
-#warning Double sided media are not supported in MediaChangeCallback
- callback.addBool( false );
-
- std::string ret = callback.evaluateStr();
-
- // "" = retry
- if (ret == "") return zypp::media::MediaChangeReport::RETRY;
-
- // "I" = ignore wrong media ID
- if (ret == "I") return zypp::media::MediaChangeReport::IGNORE_ID;
-
- // "C" = cancel
- if (ret == "C") return zypp::media::MediaChangeReport::ABORT;
-
- // "E" = eject media
- if (ret == "E") return zypp::media::MediaChangeReport::EJECT;
-
- // "S" = skip (ignore) this media
- if (ret == "S") return zypp::media::MediaChangeReport::IGNORE;
-
- // otherwise change media URL
- // try/catch to catch invalid URLs
- try {
- // set the new URL
- url = zypp::Url(ret);
-
- // remember the redirection
- MediaMap source_redir = redirect_map[url];
- source_redir[mediumNr] = url;
- redirect_map[url] = source_redir;
-
- y2milestone("Source redirected to %s", ret.c_str());
-
- return zypp::media::MediaChangeReport::CHANGE_URL;
- }
- catch ( ... )
- {
- // invalid URL, try again
- return zypp::media::MediaChangeReport::RETRY;
- }
- }
-
- // return default value from the parent class
- return zypp::media::MediaChangeReport::requestMedia(url, mediumNr, error, description);
- }
- };
-
- struct SourceCreateReceive : public Recipient, public zypp::callback::ReceiveReport<zypp::repo::RepoCreateReport>
- {
- SourceCreateReceive( RecipientCtl & construct_r ) : Recipient( construct_r ) {}
-
- virtual void reportbegin()
- {
- CB callback( ycpcb( YCPCallbacks::CB_SourceCreateInit ) );
- y2debug("Repo Create begin");
-
- if (callback._set)
- {
- callback.evaluate();
- }
- }
-
- virtual void reportend()
- {
- CB callback( ycpcb( YCPCallbacks::CB_SourceCreateDestroy ) );
- y2debug("Repo Create destroy");
-
- if (callback._set)
- {
- callback.evaluate();
- }
- }
-
- virtual void start( const zypp::Url &url )
- {
- CB callback( ycpcb( YCPCallbacks::CB_SourceCreateStart ) );
-
- if (callback._set)
- {
- callback.addStr(url);
-
- callback.evaluate();
- }
- }
-
- virtual bool progress( int value )
- {
- CB callback( ycpcb( YCPCallbacks::CB_SourceCreateProgress ) );
-
- if (callback._set)
- {
- callback.addInt(value);
-
- return callback.evaluateBool();
- }
-
- return zypp::repo::RepoCreateReport::progress(value);
- }
-
- std::string CreateSrcErrorAsString(zypp::repo::RepoCreateReport::Error error)
- {
- // convert enum to string
- std::string error_str;
-
- switch(error)
- {
- // no error
- case zypp::repo::RepoCreateReport::NO_ERROR : error_str = "NO_ERROR"; break;
- // the requested Url was not found
- case zypp::repo::RepoCreateReport::NOT_FOUND : error_str = "NOT_FOUND"; break;
- // IO error
- case zypp::repo::RepoCreateReport::IO : error_str = "IO"; break;
- // the source is invalid
- case zypp::repo::RepoCreateReport::INVALID : error_str = "INVALID"; break;
- // rejected
- case zypp::repo::RepoCreateReport::REJECTED : error_str = "REJECTED"; break;
- // unknown error
- case zypp::repo::RepoCreateReport::UNKNOWN : error_str = "UNKNOWN"; break;
- }
-
- return error_str;
- }
-
- virtual Action problem( const zypp::Url &url, zypp::repo::RepoCreateReport::Error error, const std::string &description )
- {
- CB callback( ycpcb( YCPCallbacks::CB_SourceCreateError ) );
-
- if ( callback._set )
- {
- callback.addStr(url);
- callback.addStr(CreateSrcErrorAsString(error));
- callback.addStr(description);
-
- std::string result = callback.evaluateSymbol();
-
- // check the returned symbol
- if ( result == "ABORT" ) return zypp::repo::RepoCreateReport::ABORT;
- if ( result == "RETRY" ) return zypp::repo::RepoCreateReport::RETRY;
-
- // still here?
- y2error("Unexpected symbol '%s' returned from callback.", result.c_str());
- // return default
- }
-
- // return the default implementation
- return zypp::repo::RepoCreateReport::problem(url, error, description);
- }
-
- virtual void finish( const zypp::Url &url, zypp::repo::RepoCreateReport::Error error, const std::string &reason )
- {
- CB callback( ycpcb( YCPCallbacks::CB_SourceCreateEnd ) );
-
- if (callback._set)
- {
- callback.addStr(url);
- callback.addStr(CreateSrcErrorAsString(error));
- callback.addStr(reason);
-
- callback.evaluate();
- }
- }
- };
-
- ///////////////////////////////////////////////////////////////////
- // ProbeSourceReceive
- ///////////////////////////////////////////////////////////////////
- struct ProbeSourceReceive : public Recipient, public zypp::callback::ReceiveReport<zypp::repo::ProbeRepoReport>
- {
- ProbeSourceReceive( RecipientCtl & construct_r ) : Recipient( construct_r ) {}
-
- virtual void start(const zypp::Url &url)
- {
- _silent_probing = MEDIA_CHANGE_DISABLE;
-
- CB callback( ycpcb( YCPCallbacks::CB_SourceProbeStart ) );
-
- if (callback._set)
- {
- callback.addStr(url);
-
- callback.evaluate();
- }
- }
-
- virtual void failedProbe( const zypp::Url &url, const std::string &type )
- {
- CB callback( ycpcb( YCPCallbacks::CB_SourceProbeFailed ) );
-
- if (callback._set)
- {
- callback.addStr(url);
- callback.addStr(type);
-
- callback.evaluate();
- }
- }
-
- virtual void successProbe( const zypp::Url &url, const std::string &type )
- {
- CB callback( ycpcb( YCPCallbacks::CB_SourceProbeSucceeded ) );
-
- if (callback._set)
- {
- callback.addStr(url);
- callback.addStr(type);
-
- callback.evaluate();
- }
- }
-
- std::string ProbeSrcErrorAsString(zypp::repo::ProbeRepoReport::Error error)
- {
- // convert enum to string
- std::string error_str;
-
- switch(error)
- {
- // no error
- case zypp::repo::ProbeRepoReport::NO_ERROR : error_str = "NO_ERROR"; break;
- // the requested Url was not found
- case zypp::repo::ProbeRepoReport::NOT_FOUND : error_str = "NOT_FOUND"; break;
- // IO error
- case zypp::repo::ProbeRepoReport::IO : error_str = "IO"; break;
- // the source is invalid
- case zypp::repo::ProbeRepoReport::INVALID : error_str = "INVALID"; break;
- // unknow error
- case zypp::repo::ProbeRepoReport::UNKNOWN : error_str = "UNKNOWN"; break;
- }
-
- return error_str;
- }
-
- virtual void finish(const zypp::Url &url, zypp::repo::ProbeRepoReport::Error error, const std::string &reason )
- {
- _silent_probing = MEDIA_CHANGE_FULL;
-
- CB callback( ycpcb( YCPCallbacks::CB_SourceProbeEnd ) );
-
- if (callback._set)
- {
- callback.addStr(url);
- callback.addStr(ProbeSrcErrorAsString(error));
- callback.addStr(reason);
-
- callback.evaluate();
- }
- }
-
- virtual bool progress(const zypp::Url &url, int value)
- {
- CB callback( ycpcb( YCPCallbacks::CB_SourceProbeProgress ) );
-
- if (callback._set)
- {
- callback.addStr(url);
- callback.addInt(value);
-
- return callback.evaluateBool();
- }
-
- return zypp::repo::ProbeRepoReport::progress(url, value);
- return true;
- }
-
- virtual zypp::repo::ProbeRepoReport::Action problem( const zypp::Url &url, zypp::repo::ProbeRepoReport::Error error, const std::string &description )
- {
- CB callback( ycpcb( YCPCallbacks::CB_SourceProbeError ) );
-
- if ( callback._set )
- {
- callback.addStr(url);
- callback.addStr(ProbeSrcErrorAsString(error));
- callback.addStr(description);
-
- std::string result = callback.evaluateSymbol();
-
- // check the returned symbol
- if ( result == "ABORT" ) return zypp::repo::ProbeRepoReport::ABORT;
- if ( result == "RETRY" ) return zypp::repo::ProbeRepoReport::RETRY;
-
- // still here?
- y2error("Unexpected symbol '%s' returned from callback.", result.c_str());
- // return default
- }
-
- // return the default value
- return zypp::repo::ProbeRepoReport::problem(url, error, description);
- }
- };
-
-
- struct RepoReport : public Recipient, public zypp::callback::ReceiveReport<zypp::repo::RepoReport>
- {
- const PkgModuleFunctions &_pkg_ref;
- virtual void reportbegin()
- {
- CB callback( ycpcb( YCPCallbacks::CB_SourceReportInit ) );
- y2debug("Source Report begin");
-
- if (callback._set)
- {
- callback.evaluate();
- }
- }
-
- virtual void reportend()
- {
- CB callback( ycpcb( YCPCallbacks::CB_SourceReportDestroy ) );
- y2debug("Source Report end");
-
- if (callback._set)
- {
- callback.evaluate();
- }
- }
-
- RepoReport( RecipientCtl & construct_r, const PkgModuleFunctions &pk ) : Recipient( construct_r ), _pkg_ref(pk) {}
-
- virtual void start(const zypp::ProgressData &task, const zypp::RepoInfo repo)
- {
- CB callback( ycpcb( YCPCallbacks::CB_SourceReportStart ) );
-
- if (callback._set)
- {
- callback.addInt(_pkg_ref.logFindAlias(repo.alias()));
-
- std::string url;
- if (repo.baseUrlsBegin() != repo.baseUrlsEnd())
- {
- url = repo.baseUrlsBegin()->asString();
- }
-
- callback.addStr(url);
- callback.addStr(task.name());
-
- callback.evaluate();
- }
- }
-
- virtual bool progress(const zypp::ProgressData &task)
- {
- CB callback( ycpcb( YCPCallbacks::CB_SourceReportProgress ) );
-
- if (callback._set)
- {
- callback.addInt(task.reportValue());
-
- return callback.evaluateBool();
- }
-
- return zypp::repo::RepoReport::progress(task);
- }
-
- std::string SrcReportErrorAsString(zypp::repo::RepoReport::Error error)
- {
- // convert enum to string
- std::string error_str;
-
- switch(error)
- {
- // no error
- case zypp::repo::RepoReport::NO_ERROR : error_str = "NO_ERROR"; break;
- // the requested Url was not found
- case zypp::repo::RepoReport::NOT_FOUND : error_str = "NOT_FOUND"; break;
- // IO error
- case zypp::repo::RepoReport::IO : error_str = "IO"; break;
- // the source is invalid
- case zypp::repo::RepoReport::INVALID : error_str = "INVALID"; break;
- }
-
- return error_str;
- }
-
- virtual zypp::repo::RepoReport::Action problem(zypp::Repository source,
- zypp::repo::RepoReport::Error error, const std::string &description)
- {
- CB callback( ycpcb( YCPCallbacks::CB_SourceReportError ) );
-
- // the file is optional, ignore the error
- if (_silent_probing == ZyppRecipients::MEDIA_CHANGE_OPTIONALFILE)
- {
- y2milestone("The file is optional, ignoring the error");
- return zypp::repo::RepoReport::IGNORE;
- }
-
- if ( callback._set )
- {
- // search Yast source ID
- callback.addInt(_pkg_ref.logFindAlias(source.info().alias()));
-
- std::string url;
- if (source.info().baseUrlsBegin() != source.info().baseUrlsEnd())
- {
- url = source.info().baseUrlsBegin()->asString();
- }
-
- callback.addStr(url);
- callback.addStr(SrcReportErrorAsString(error));
- callback.addStr(description);
-
- std::string result = callback.evaluateSymbol();
-
- // check the returned symbol
- if ( result == "ABORT" ) return zypp::repo::RepoReport::ABORT;
- if ( result == "RETRY" ) return zypp::repo::RepoReport::RETRY;
- if ( result == "IGNORE" ) return zypp::repo::RepoReport::IGNORE;
-
- // still here?
- y2error("Unexpected symbol '%s' returned from callback.", result.c_str());
- // return default
- }
-
- // return the default value
- return zypp::repo::RepoReport::problem(source, error, description);
- }
-
- virtual void finish(zypp::Repository source, const std::string &task,
- zypp::repo::RepoReport::Error error, const std::string &reason)
- {
- CB callback( ycpcb( YCPCallbacks::CB_SourceReportEnd ) );
-
- if (callback._set)
- {
- // search Yast source ID
- callback.addInt(_pkg_ref.logFindAlias(source.info().alias()));
-
- std::string url;
- if (source.info().baseUrlsBegin() != source.info().baseUrlsEnd())
- {
- url = source.info().baseUrlsBegin()->asString();
- }
- callback.addStr(url);
-
- callback.addStr(task);
- callback.addStr(SrcReportErrorAsString(error));
- callback.addStr(reason);
-
- callback.evaluate();
- }
- }
- };
-
-
- struct ResolvableReport : public Recipient, public zypp::callback::ReceiveReport<zypp::target::MessageResolvableReport>
- {
- ResolvableReport( RecipientCtl & construct_r ) : Recipient( construct_r ) {}
-
- virtual void show(zypp::Message::constPtr message)
- {
- CB callback( ycpcb( YCPCallbacks::CB_ResolvableReport) );
-
- if (callback._set)
- {
- zypp::Patch::constPtr patch = message->patch();
-
- // patch name
- callback.addStr(patch ? patch->name() : message->name());
- // patch summary
- callback.addStr(patch ? patch->summary() : message->summary());
- // message itself
- callback.addStr(message->text().asString());
-
- callback.evaluate();
- }
- }
- };
-
- ///////////////////////////////////////////////////////////////////
- // DigestReport handler
- ///////////////////////////////////////////////////////////////////
- struct DigestReceive : public Recipient, public zypp::callback::ReceiveReport<zypp::DigestReport>
- {
- DigestReceive( RecipientCtl & construct_r ) : Recipient( construct_r ) {}
-
- virtual bool askUserToAcceptNoDigest( const zypp::Pathname &file )
- {
- CB callback( ycpcb( YCPCallbacks::CB_AcceptFileWithoutChecksum) );
-
- if (callback._set)
- {
- callback.addStr(file.asString());
-
- return callback.evaluateBool();
- }
-
- return zypp::DigestReport::askUserToAcceptNoDigest(file);
- }
-
- virtual bool askUserToAccepUnknownDigest( const zypp::Pathname &file, const std::string &name )
- {
- CB callback( ycpcb( YCPCallbacks::CB_AcceptUnknownDigest) );
-
- if (callback._set)
- {
- callback.addStr(file.asString());
- callback.addStr(name);
-
- return callback.evaluateBool();
- }
-
- return zypp::DigestReport::askUserToAccepUnknownDigest(file, name);
- }
-
- virtual bool askUserToAcceptWrongDigest( const zypp::Pathname &file, const std::string &requested, const std::string &found )
- {
- CB callback( ycpcb( YCPCallbacks::CB_AcceptWrongDigest) );
-
- if (callback._set)
- {
- callback.addStr(file.asString());
- callback.addStr(requested);
- callback.addStr(found);
-
- return callback.evaluateBool();
- }
-
- return zypp::DigestReport::askUserToAcceptWrongDigest(file, requested, found);
- }
-
- };
-
-
- ///////////////////////////////////////////////////////////////////
- // KeyRingReport handler
- ///////////////////////////////////////////////////////////////////
- struct KeyRingReceive : public Recipient, public zypp::callback::ReceiveReport<zypp::KeyRingReport>
- {
- KeyRingReceive( RecipientCtl & construct_r ) : Recipient( construct_r ) {}
-
- virtual bool askUserToImportKey( const zypp::PublicKey &key)
- {
- CB callback( ycpcb( YCPCallbacks::CB_ImportGpgKey) );
-
- if (callback._set)
- {
- callback.addStr(key.id());
- callback.addStr(key.name());
- callback.addStr(key.fingerprint());
-
- bool res = callback.evaluateBool();
- y2milestone("Callback ImportGpgKey value: %s", res ? "true" : "false");
-
- return res;
- }
-
- y2milestone("Callback ImportGpgKey not registered, using default value: %s", zypp::KeyRingReport::askUserToImportKey(key) ? "true" : "false");
-
- return zypp::KeyRingReport::askUserToImportKey(key);
- }
-
- virtual bool askUserToTrustKey(const zypp::PublicKey& key)
- {
- CB callback( ycpcb( YCPCallbacks::CB_AcceptNonTrustedGpgKey) );
-
- if (callback._set)
- {
- callback.addStr(key.path().asString());
- callback.addStr(key.id());
-
- callback.addStr(key.name());
- callback.addStr(key.fingerprint());
-
- bool res = callback.evaluateBool();
- y2milestone("Callback AcceptNonTrustedGpgKey value: %s", res ? "true" : "false");
-
- return res;
- }
-
- y2milestone("Callback AcceptNonTrustedGpgKey not registered, using default value: %s", zypp::KeyRingReport::askUserToTrustKey(key) ? "true" : "false");
-
- return zypp::KeyRingReport::askUserToTrustKey(key);
- }
-
- virtual bool askUserToAcceptUnsignedFile(const std::string &file)
- {
- CB callback( ycpcb( YCPCallbacks::CB_AcceptUnsignedFile) );
-
- if (callback._set)
- {
- callback.addStr(file);
-
- return callback.evaluateBool();
- }
-
- return zypp::KeyRingReport::askUserToAcceptUnsignedFile(file);
- }
-
- virtual bool askUserToAcceptUnknownKey(const std::string &file, const std::string &id)
- {
- CB callback( ycpcb( YCPCallbacks::CB_AcceptUnknownGpgKey) );
-
- if (callback._set)
- {
- callback.addStr(file);
- callback.addStr(id);
-
- bool res = callback.evaluateBool();
- y2milestone("Callback AcceptUnknownGpgKey value: %s", res ? "true" : "false");
-
- return res;
- }
-
- y2milestone("Callback AcceptUnknownGpgKey is not registered, using default value: %s", zypp::KeyRingReport::askUserToAcceptUnknownKey(file,id) ? "true" : "false");
-
- return zypp::KeyRingReport::askUserToAcceptUnknownKey(file,id);
- }
-
- virtual bool askUserToAcceptVerificationFailed(const std::string &file, const zypp::PublicKey &key)
- {
- CB callback( ycpcb( YCPCallbacks::CB_AcceptVerificationFailed) );
-
- if (callback._set)
- {
- callback.addStr(file);
- callback.addStr(key.id());
- callback.addStr(key.name());
- callback.addStr(key.fingerprint());
-
- return callback.evaluateBool();
- }
-
- return zypp::KeyRingReport::askUserToAcceptVerificationFailed(file, key);
- }
- };
-
- ///////////////////////////////////////////////////////////////////
- // KeyRingSignals handler
- ///////////////////////////////////////////////////////////////////
- struct KeyRingSignal : public Recipient, public zypp::callback::ReceiveReport<zypp::KeyRingSignals>
- {
- KeyRingSignal ( RecipientCtl & construct_r ) : Recipient( construct_r ) {}
-
- virtual void trustedKeyAdded( const zypp::PublicKey &key )
- {
- CB callback( ycpcb( YCPCallbacks::CB_TrustedKeyAdded) );
-
- if (callback._set)
- {
- callback.addStr(key.id());
- callback.addStr(key.name());
- callback.addStr(key.fingerprint());
- }
- }
-
- virtual void trustedKeyRemoved( const zypp::PublicKey &key )
- {
- CB callback( ycpcb( YCPCallbacks::CB_TrustedKeyRemoved) );
-
- if (callback._set)
- {
- callback.addStr(key.id());
- callback.addStr(key.name());
- callback.addStr(key.fingerprint());
- }
- }
- };
-
-
-///////////////////////////////////////////////////////////////////
-}; // namespace ZyppRecipients
-///////////////////////////////////////////////////////////////////
-
-///////////////////////////////////////////////////////////////////
-//
-// CLASS NAME : PkgModuleFunctions::CallbackHandler::ZyppReceive
-/**
- * @short Manages the Y2PMCallbacks we receive.
- *
- **/
-class PkgModuleFunctions::CallbackHandler::ZyppReceive : public ZyppRecipients::RecipientCtl {
-
- private:
-
- // RRM DB callbacks
- ZyppRecipients::ConvertDbReceive _convertDbReceive;
- ZyppRecipients::RebuildDbReceive _rebuildDbReceive;
- ZyppRecipients::ScanDbReceive _scanDbReceive;
-
- // package callbacks
- ZyppRecipients::InstallPkgReceive _installPkgReceive;
- ZyppRecipients::RemovePkgReceive _removePkgReceive;
- ZyppRecipients::DownloadResolvableReceive _providePkgReceive;
-
- // media callback
- ZyppRecipients::MediaChangeReceive _mediaChangeReceive;
- ZyppRecipients::DownloadProgressReceive _downloadProgressReceive;
-
- // script/messages
- ZyppRecipients::ScriptExecReceive _scriptExecReceive;
- ZyppRecipients::MessageReceive _messageReceive;
-
- // source manager callback
- ZyppRecipients::SourceCreateReceive _sourceCreateReceive;
- ZyppRecipients::RepoReport _sourceReport;
- ZyppRecipients::ProbeSourceReceive _probeSourceReceive;
-
- ZyppRecipients::ProgressReceive _progressReceive;
-
- // resolvable report
- ZyppRecipients::ResolvableReport _resolvableReport;
-
- // digest callback
- ZyppRecipients::DigestReceive _digestReceive;
-
- // key ring callback
- ZyppRecipients::KeyRingReceive _keyRingReceive;
-
- // key ring signal callback
- ZyppRecipients::KeyRingSignal _keyRingSignal;
-
- // authentication callback
- ZyppRecipients::AuthReceive _authReceive;
-
- public:
-
- ZyppReceive( const YCPCallbacks & ycpcb_r, const PkgModuleFunctions &pkg)
- : RecipientCtl( ycpcb_r )
- , _convertDbReceive( *this )
- , _rebuildDbReceive( *this )
- , _scanDbReceive( *this )
- , _installPkgReceive( *this )
- , _removePkgReceive( *this )
- , _providePkgReceive( *this, pkg )
- , _mediaChangeReceive( *this )
- , _downloadProgressReceive( *this )
- , _scriptExecReceive( *this )
- , _messageReceive( *this )
- , _sourceCreateReceive( *this )
- , _sourceReport( *this, pkg)
- , _probeSourceReceive( *this )
- , _progressReceive( *this )
- , _resolvableReport( *this )
- , _digestReceive( *this )
- , _keyRingReceive( *this )
- , _keyRingSignal( *this )
- , _authReceive( *this )
- {
- // connect the receivers
- _convertDbReceive.connect();
- _rebuildDbReceive.connect();
- _scanDbReceive.connect();
- _installPkgReceive.connect();
- _removePkgReceive.connect();
- _providePkgReceive.connect();
- _mediaChangeReceive.connect();
- _downloadProgressReceive.connect();
- _scriptExecReceive.connect();
- _messageReceive.connect();
- _sourceCreateReceive.connect();
- _sourceReport.connect();
- _probeSourceReceive.connect();
- _progressReceive.connect();
- _resolvableReport.connect();
- _digestReceive.connect();
- _keyRingReceive.connect();
- _keyRingSignal.connect();
- _authReceive.connect();
- }
-
- virtual ~ZyppReceive()
- {
- // disconnect the receivers
- _convertDbReceive.disconnect();
- _rebuildDbReceive.disconnect();
- _scanDbReceive.disconnect();
- _installPkgReceive.disconnect();
- _removePkgReceive.disconnect();
- _providePkgReceive.disconnect();
- _mediaChangeReceive.disconnect();
- _downloadProgressReceive.disconnect();
- _scriptExecReceive.disconnect();
- _messageReceive.disconnect();
- _sourceCreateReceive.disconnect();
- _sourceReport.disconnect();
- _probeSourceReceive.disconnect();
- _progressReceive.disconnect();
- _resolvableReport.disconnect();
- _digestReceive.disconnect();
- _keyRingReceive.disconnect();
- _keyRingSignal.disconnect();
- _authReceive.disconnect();
- }
- public:
-
-};
-
-///////////////////////////////////////////////////////////////////
-//
-// CLASS NAME : PkgModuleFunctions::CallbackHandler
-//
-///////////////////////////////////////////////////////////////////
-
-///////////////////////////////////////////////////////////////////
-//
-//
-// METHOD NAME : PkgModuleFunctions::CallbackHandler::CallbackHandler
-// METHOD TYPE : Constructor
-//
-PkgModuleFunctions::CallbackHandler::CallbackHandler(const PkgModuleFunctions &pk)
- : _ycpCallbacks( *new YCPCallbacks() )
- , _zyppReceive( *new ZyppReceive(_ycpCallbacks, pk) )
-{
-}
-
-///////////////////////////////////////////////////////////////////
-//
-//
-// METHOD NAME : PkgModuleFunctions::CallbackHandler::~CallbackHandler
-// METHOD TYPE : Destructor
-//
-PkgModuleFunctions::CallbackHandler::~CallbackHandler()
-{
- y2debug("Deleting callback handler");
- delete &_zyppReceive;
- delete &_ycpCallbacks;
-}
///////////////////////////////////////////////////////////////////
//
Copied: trunk/pkg-bindings/src/Locale.cc (from r42212, trunk/pkg-bindings/src/PkgModuleFunctions.cc)
URL: http://svn.opensuse.org/viewcvs/yast/trunk/pkg-bindings/src/Locale.cc?p2=tr…
==============================================================================
--- trunk/pkg-bindings/src/PkgModuleFunctions.cc (original)
+++ trunk/pkg-bindings/src/Locale.cc Thu Dec 6 07:56:58 2007
@@ -21,344 +21,11 @@
/-*/
-#include <ycp/YExpression.h>
-#include <ycp/YBlock.h>
#include "PkgModuleFunctions.h"
#include "Callbacks.h"
-#include <ycp/YCPInteger.h>
-#include <ycp/YCPString.h>
-#include <ycp/YCPBoolean.h>
-#include <ycp/YCPMap.h>
-#include <ycp/YCPVoid.h>
-
-#include <zypp/ZYppFactory.h>
-#include <zypp/ResPool.h>
-#include <zypp/RepoInfo.h>
-#include <zypp/MediaSetAccess.h>
-
-// sleep
-#include <unistd.h>
-
-// exit
-#include <cstdlib>
-
-// textdomain
-#include <libintl.h>
-
-class Y2PkgFunction: public Y2Function
-{
- unsigned int m_position;
- PkgModuleFunctions* m_instance;
- YCPValue m_param1;
- YCPValue m_param2;
- YCPValue m_param3;
- YCPValue m_param4;
- YCPValue m_param5;
- string m_name;
-public:
-
- Y2PkgFunction (string name, PkgModuleFunctions* instance, unsigned int pos);
- bool attachParameter (const YCPValue& arg, const int position);
- constTypePtr wantedParameterType () const;
- bool appendParameter (const YCPValue& arg);
- bool finishParameters ();
- YCPValue evaluateCall ();
- bool reset ();
- string name () const;
-};
-
-
- Y2PkgFunction::Y2PkgFunction (string name, PkgModuleFunctions* instance, unsigned int pos) :
- m_position (pos)
- , m_instance (instance)
- , m_param1 ( YCPNull () )
- , m_param2 ( YCPNull () )
- , m_param3 ( YCPNull () )
- , m_param4 ( YCPNull () )
- , m_param5 ( YCPNull () )
- , m_name (name)
- {
- };
-
- bool Y2PkgFunction::attachParameter (const YCPValue& arg, const int position)
- {
- switch (position)
- {
- case 0: m_param1 = arg; break;
- case 1: m_param2 = arg; break;
- case 2: m_param3 = arg; break;
- case 3: m_param4 = arg; break;
- case 4: m_param5 = arg; break;
- default: return false;
- }
-
- return true;
- }
-
- constTypePtr Y2PkgFunction::wantedParameterType () const
- {
- y2internal ("wantedParameterType not implemented");
- return Type::Unspec;
- }
-
- bool Y2PkgFunction::appendParameter (const YCPValue& arg)
- {
- if (m_param1.isNull ())
- {
- m_param1 = arg;
- return true;
- } else if (m_param2.isNull ())
- {
- m_param2 = arg;
- return true;
- } else if (m_param3.isNull ())
- {
- m_param3 = arg;
- return true;
- } else if (m_param4.isNull ())
- {
- m_param4 = arg;
- return true;
- }
- else if (m_param5.isNull ())
- {
- m_param5 = arg;
- return true;
- }
- y2internal ("appendParameter > 5 not implemented");
- return false;
- }
-
- bool Y2PkgFunction::finishParameters ()
- {
- y2internal ("finishParameters not implemented");
- return true;
- }
-
- YCPValue Y2PkgFunction::evaluateCall ()
- {
- ycpmilestone ("Pkg Builtin called: %s", name().c_str() );
-
- try
- {
- switch (m_position) {
-#include "PkgBuiltinCalls.h"
- }
- }
- catch (const std::exception& excpt)
- {
- y2internal("Caught an unhandled exception: %s", excpt.what());
- }
- catch (...)
- {
- y2internal("Caught an unhandled exception");
- }
-
- return YCPNull ();
- }
-
- bool Y2PkgFunction::reset ()
- {
- m_param1 = YCPNull ();
- m_param2 = YCPNull ();
- m_param3 = YCPNull ();
- m_param4 = YCPNull ();
- m_param5 = YCPNull ();
-
- return true;
- }
-
- string Y2PkgFunction::name () const
- {
- return m_name;
- }
-
-/////////////////////////////////////////////////////////////////////////////
-//
-// Class: YRepo
-//
-
-IMPL_PTR_TYPE(YRepo);
-
-YRepo::YRepo(zypp::RepoInfo & repo)
- : _repo(repo), _deleted(false)
-{}
-
-YRepo::~YRepo()
-{
- if (_maccess)
- {
- try { _maccess->release(); }
- catch (const zypp::media::MediaException & ex)
- {
- y2error("Error in ~Yrepo(): %s", ex.asString().c_str());
- }
- }
-}
-
-zypp::MediaSetAccess_Ptr & YRepo::mediaAccess()
-{
- if (!_maccess)
- {
- y2milestone("Creating new MediaSetAccess for url %s",
- (*_repo.baseUrlsBegin()).asString().c_str());
- _maccess = new zypp::MediaSetAccess(*_repo.baseUrlsBegin()); // FIXME handle multiple baseUrls
- }
-
- return _maccess;
-}
-
-const YRepo YRepo::NOREPO;
-
-/////////////////////////////////////////////////////////////////////////////
-
-
-const zypp::ResStatus::TransactByValue PkgModuleFunctions::whoWantsIt = zypp::ResStatus::APPL_HIGH;
-
-/**
- * Constructor.
- */
-PkgModuleFunctions::PkgModuleFunctions ()
- : Y2Namespace()
- , _target_root( "/" )
- , zypp_pointer(NULL)
- ,_callbackHandler( *new CallbackHandler(*this) )
-{
- registerFunctions ();
-
- const char *domain = "pkg-bindings";
- bindtextdomain( domain, LOCALEDIR );
- bind_textdomain_codeset( domain, "utf8" );
- textdomain( domain );
-
- // Make change known.
- {
- extern int _nl_msg_cat_cntr;
- ++_nl_msg_cat_cntr;
- }
-}
-
-/**
- * Connect to Zypp library if it is not already connected.
- */
-zypp::ZYpp::Ptr PkgModuleFunctions::zypp_ptr()
-{
- if (zypp_pointer != NULL)
- {
- return zypp_pointer;
- }
-
- int max_count = 5;
- unsigned int seconds = 3;
-
- while (zypp_pointer == NULL && max_count > 0)
- {
- try
- {
- y2milestone("Initializing Zypp library...");
- zypp_pointer = zypp::getZYpp();
- return zypp_pointer;
- }
- catch (...)
- {
- }
-
- max_count--;
-
- if (zypp_pointer == NULL && max_count > 0)
- {
- sleep(seconds);
- }
- }
-
- // still not initialized, throw an exception
- ZYPP_THROW (zypp::Exception(std::string("Cannot connect to the package manager")));
-
- return zypp_pointer;
-}
-
-
-/**
- * Destructor.
- */
-PkgModuleFunctions::~PkgModuleFunctions ()
-{
- delete &_callbackHandler;
-
- if (zypp_pointer != NULL)
- {
- try
- {
- y2milestone("Finishing the target");
- zypp_pointer->finishTarget();
- }
- catch(...)
- {
- y2error("finishTarget() has failed");
- }
-
- y2milestone("Releasing the zypp pointer...");
- zypp_pointer = NULL;
- y2milestone("Zypp pointer released");
- }
-}
-
-Y2Function* PkgModuleFunctions::createFunctionCall (const string name, constFunctionTypePtr type)
-{
- vector<string>::iterator it = find (_registered_functions.begin ()
- , _registered_functions.end (), name);
- if (it == _registered_functions.end ())
- {
- y2error ("No such function %s", name.c_str ());
- return NULL;
- }
-
- return new Y2PkgFunction (name, this, it - _registered_functions.begin ());
-}
-
-void PkgModuleFunctions::registerFunctions()
-{
-#include "PkgBuiltinTable.h"
-}
-
-
-// ------------------------------------------------------------------
-// general
-
-/**
- * @builtin Connect
- * @short Explicitly connect to the package manager, if it is already connected do nothing
- * @description Checks whether the package manager is connected to Yast,
- * if not try connecting to it.
- * @return boolean true if the package manager is connected
- */
-YCPValue
-PkgModuleFunctions::Connect()
-{
- try
- {
- return YCPBoolean(zypp_ptr() != NULL);
- }
- catch(...)
- {
- }
-
- return YCPBoolean(false);
-}
-
-/**
- * @builtin InstSysMode
- * @short obsoleted - do not use
- * @return void
- */
-YCPValue
-PkgModuleFunctions::InstSysMode ()
-{
- y2warning("Pkg::InstSysMode() is obsoleted, it's not needed anymore");
- return YCPVoid();
-}
+#include <zypp/Locale.h>
/**
* @builtin SetTextLocale
@@ -577,140 +244,3 @@
return langycplist;
}
-
-/**
- * @builtin LastError
- *
- * @short get current error as string
- * @return string
- */
-YCPValue
-PkgModuleFunctions::LastError ()
-{
- return YCPString(_last_error.lastError());
-}
-
-/**
- * @builtin LastErrorDetails
- *
- * @short get current error details as string
- * @return string Error Details
- */
-YCPValue
-PkgModuleFunctions::LastErrorDetails ()
-{
- return YCPString (_last_error.lastErrorDetails());
-}
-
-/**
- * @builtin LastErrorId
- * @short Obsoleted function, do not use
- * @return string
- */
-YCPValue
-PkgModuleFunctions::LastErrorId ()
-{
-
- /* TODO FIXME
- int errorId = _last_error;
- switch ( errorId ) {
- case PMError::E_ok:
- return YCPString( "ok" );
- case InstSrcError::E_isrc_cache_duplicate:
- return YCPString( "instsrc_duplicate" );
- default:
- return YCPString( "error" );
- }
- */
-
- return YCPString( "ok" );
-}
-
-/**
- * @builtin Init
- * @short completely initialize package management (currently it is empty)
- * @return boolean true on success
- */
-YCPValue
-PkgModuleFunctions::Init ()
-{
-#warning FIXME can be Init() empty??
- return YCPBoolean(true);
-}
-
-zypp::RepoManager PkgModuleFunctions::CreateRepoManager()
-{
- // set path option, use root dir as a prefix for the default directory
- zypp::RepoManagerOptions repo_options;
- repo_options.knownReposPath = zypp::Pathname(_target_root) + repo_options.knownReposPath;
-
- y2milestone("Path to repository files: %s", repo_options.knownReposPath.asString().c_str());
-
- return zypp::RepoManager(repo_options);
-}
-
-// convert Exception object to string represenatation
-std::string PkgModuleFunctions::ExceptionAsString(const zypp::Exception &e)
-{
- std::string ret = e.asUserString();
-
- if (e.historySize() > 0)
- {
- ret += "\n" + e.historyAsString();
- }
-
- y2debug("Error message: %s", ret.c_str());
-
- return ret;
-}
-
-
-/** ------------------------
- * Convert InstSrcDescr to product info YCPMap:
- * <TABLE>
- * <TR><TD>$[<TD>"product" <TD>: YCPString (name' 'version)
- * <TR><TD>,<TD>"vendor" <TD>: YCPString
- * <TR><TD>,<TD>"requires" <TD>: YCPString
- * <TR><TD>,<TD>"name" <TD>: YCPString
- * <TR><TD>,<TD>"version" <TD>: YCPString
- * <TR><TD>,<TD>"flags" <TD>: YCPString
- * <TR><TD>,<TD>"relnotesurl" <TD>: YCPString
- * <TR><TD>,<TD>"distproduct" <TD>: YCPString
- * <TR><TD>,<TD>"distversion" <TD>: YCPString
- * <TR><TD>,<TD>"baseproduct" <TD>: YCPString
- * <TR><TD>,<TD>"baseversion" <TD>: YCPString
- * <TR><TD>];
- * </TABLE>
-
-
-YCPMap
-PkgModuleFunctions::Descr2Map (constInstSrcDescrPtr descr)
-{
- YCPMap map;
-
- map->add (YCPString ("product"), YCPString (descr->content_product().asPkgNameEd().name.asString()
- + " "
- + descr->content_product().asPkgNameEd().edition.version()));
- map->add (YCPString ("vendor"), YCPString (descr->content_vendor()));
- map->add (YCPString ("requires"), YCPString (descr->content_requires().asString()));
-
- // for installation/modules/Product.ycp
- map->add (YCPString ("name"), YCPString (descr->content_product().asPkgNameEd().name));
- map->add (YCPString ("version"), YCPString (descr->content_product().asPkgNameEd().edition.version()));
- map->add (YCPString ("flags"), YCPString (descr->content_flags()));
- map->add (YCPString ("relnotesurl"), YCPString (descr->content_relnotesurl()));
-
- // vendor already in map
-
- map->add (YCPString ("distproduct"), YCPString (descr->content_distproduct().name));
- map->add (YCPString ("distversion"), YCPString (descr->content_distproduct().edition.version()));
-
- map->add (YCPString ("baseproduct"), YCPString (descr->content_baseproduct().asPkgNameEd().name));
- map->add (YCPString ("baseversion"), YCPString (descr->content_baseproduct().asPkgNameEd().edition.version()));
-
- map->add (YCPString ("defaultbase"), YCPString (descr->content_defaultbase()));
-
- return map;
-}
-*/
-
Modified: trunk/pkg-bindings/src/Makefile.am
URL: http://svn.opensuse.org/viewcvs/yast/trunk/pkg-bindings/src/Makefile.am?rev…
==============================================================================
--- trunk/pkg-bindings/src/Makefile.am (original)
+++ trunk/pkg-bindings/src/Makefile.am Thu Dec 6 07:56:58 2007
@@ -25,16 +25,29 @@
PkgProgress.cc PkgProgress.h \
PkgModuleFunctions.h \
PkgModuleFunctions.cc \
+ PkgModuleFunctions_Register.cc \
Package.cc \
Patch.cc \
Resolvable.cc \
Selection.cc \
Target.cc \
- Source.cc \
+ Locale.cc \
+ Source_Callbacks.cc \
+ Source_Create.cc \
+ Source_Download.cc \
+ Source_Get.cc \
+ Source_Installation.cc \
+ Source_Load.cc \
+ Source_Misc.cc \
+ Source_Resolvables.cc \
+ Source_Save.cc \
+ Source_Set.cc \
Keyring.cc \
Callbacks.h \
- Callbacks.YCP.h \
- Callbacks.cc
+ Callbacks.YCP.h Callbacks.YCP.cc \
+ Callbacks.cc Callbacks_Register.cc \
+ Y2PkgFunction.cc Y2PkgFunction.h \
+ YRepo.h YRepo.cc
libpy2Pkg_la_LDFLAGS = -version-info 2:0
Modified: trunk/pkg-bindings/src/PkgModuleFunctions.cc
URL: http://svn.opensuse.org/viewcvs/yast/trunk/pkg-bindings/src/PkgModuleFuncti…
==============================================================================
--- trunk/pkg-bindings/src/PkgModuleFunctions.cc (original)
+++ trunk/pkg-bindings/src/PkgModuleFunctions.cc Thu Dec 6 07:56:58 2007
@@ -21,8 +21,7 @@
/-*/
-#include <ycp/YExpression.h>
-#include <ycp/YBlock.h>
+#include <y2/Y2Function.h>
#include "PkgModuleFunctions.h"
#include "Callbacks.h"
@@ -34,183 +33,15 @@
#include <ycp/YCPVoid.h>
#include <zypp/ZYppFactory.h>
-#include <zypp/ResPool.h>
-#include <zypp/RepoInfo.h>
-#include <zypp/MediaSetAccess.h>
// sleep
#include <unistd.h>
-// exit
-#include <cstdlib>
-
// textdomain
#include <libintl.h>
-class Y2PkgFunction: public Y2Function
-{
- unsigned int m_position;
- PkgModuleFunctions* m_instance;
- YCPValue m_param1;
- YCPValue m_param2;
- YCPValue m_param3;
- YCPValue m_param4;
- YCPValue m_param5;
- string m_name;
-public:
-
- Y2PkgFunction (string name, PkgModuleFunctions* instance, unsigned int pos);
- bool attachParameter (const YCPValue& arg, const int position);
- constTypePtr wantedParameterType () const;
- bool appendParameter (const YCPValue& arg);
- bool finishParameters ();
- YCPValue evaluateCall ();
- bool reset ();
- string name () const;
-};
-
-
- Y2PkgFunction::Y2PkgFunction (string name, PkgModuleFunctions* instance, unsigned int pos) :
- m_position (pos)
- , m_instance (instance)
- , m_param1 ( YCPNull () )
- , m_param2 ( YCPNull () )
- , m_param3 ( YCPNull () )
- , m_param4 ( YCPNull () )
- , m_param5 ( YCPNull () )
- , m_name (name)
- {
- };
-
- bool Y2PkgFunction::attachParameter (const YCPValue& arg, const int position)
- {
- switch (position)
- {
- case 0: m_param1 = arg; break;
- case 1: m_param2 = arg; break;
- case 2: m_param3 = arg; break;
- case 3: m_param4 = arg; break;
- case 4: m_param5 = arg; break;
- default: return false;
- }
-
- return true;
- }
-
- constTypePtr Y2PkgFunction::wantedParameterType () const
- {
- y2internal ("wantedParameterType not implemented");
- return Type::Unspec;
- }
-
- bool Y2PkgFunction::appendParameter (const YCPValue& arg)
- {
- if (m_param1.isNull ())
- {
- m_param1 = arg;
- return true;
- } else if (m_param2.isNull ())
- {
- m_param2 = arg;
- return true;
- } else if (m_param3.isNull ())
- {
- m_param3 = arg;
- return true;
- } else if (m_param4.isNull ())
- {
- m_param4 = arg;
- return true;
- }
- else if (m_param5.isNull ())
- {
- m_param5 = arg;
- return true;
- }
- y2internal ("appendParameter > 5 not implemented");
- return false;
- }
-
- bool Y2PkgFunction::finishParameters ()
- {
- y2internal ("finishParameters not implemented");
- return true;
- }
-
- YCPValue Y2PkgFunction::evaluateCall ()
- {
- ycpmilestone ("Pkg Builtin called: %s", name().c_str() );
-
- try
- {
- switch (m_position) {
-#include "PkgBuiltinCalls.h"
- }
- }
- catch (const std::exception& excpt)
- {
- y2internal("Caught an unhandled exception: %s", excpt.what());
- }
- catch (...)
- {
- y2internal("Caught an unhandled exception");
- }
-
- return YCPNull ();
- }
-
- bool Y2PkgFunction::reset ()
- {
- m_param1 = YCPNull ();
- m_param2 = YCPNull ();
- m_param3 = YCPNull ();
- m_param4 = YCPNull ();
- m_param5 = YCPNull ();
-
- return true;
- }
+#include "Y2PkgFunction.h";
- string Y2PkgFunction::name () const
- {
- return m_name;
- }
-
-/////////////////////////////////////////////////////////////////////////////
-//
-// Class: YRepo
-//
-
-IMPL_PTR_TYPE(YRepo);
-
-YRepo::YRepo(zypp::RepoInfo & repo)
- : _repo(repo), _deleted(false)
-{}
-
-YRepo::~YRepo()
-{
- if (_maccess)
- {
- try { _maccess->release(); }
- catch (const zypp::media::MediaException & ex)
- {
- y2error("Error in ~Yrepo(): %s", ex.asString().c_str());
- }
- }
-}
-
-zypp::MediaSetAccess_Ptr & YRepo::mediaAccess()
-{
- if (!_maccess)
- {
- y2milestone("Creating new MediaSetAccess for url %s",
- (*_repo.baseUrlsBegin()).asString().c_str());
- _maccess = new zypp::MediaSetAccess(*_repo.baseUrlsBegin()); // FIXME handle multiple baseUrls
- }
-
- return _maccess;
-}
-
-const YRepo YRepo::NOREPO;
/////////////////////////////////////////////////////////////////////////////
@@ -318,12 +149,6 @@
return new Y2PkgFunction (name, this, it - _registered_functions.begin ());
}
-void PkgModuleFunctions::registerFunctions()
-{
-#include "PkgBuiltinTable.h"
-}
-
-
// ------------------------------------------------------------------
// general
@@ -349,236 +174,6 @@
}
/**
- * @builtin InstSysMode
- * @short obsoleted - do not use
- * @return void
- */
-YCPValue
-PkgModuleFunctions::InstSysMode ()
-{
- y2warning("Pkg::InstSysMode() is obsoleted, it's not needed anymore");
- return YCPVoid();
-}
-
-/**
- * @builtin SetTextLocale
- * @short Set Package Manager Locale
- * @description
- * Set the given locale as the output locale -- all messages from the package manager (errors, warnings,...)
- * will be returned in the selected language. This built-in does not change package selection in any way.
- * @param string locale Locale
- * @return void
- */
-YCPValue
-PkgModuleFunctions::SetTextLocale (const YCPString &locale)
-{
- try
- {
- zypp::Locale loc = zypp::Locale(locale->value());
- zypp_ptr()->setTextLocale(loc);
- }
- catch (const std::exception& excpt)
- {
- y2error("Caught an exception: %s", excpt.what());
- }
- catch (...)
- {
- y2internal("Caught an unknown exception");
- }
-
- return YCPVoid();
-}
-
-/**
- * @builtin SetPackageLocale
- * @short Select locale for installation
- * @description
- * Select the main locale for installation, call Pkg::PkgSolve() to select the respective packages.
- * @param string locale Locale
- * @return void
- */
-YCPValue
-PkgModuleFunctions::SetPackageLocale (const YCPString &locale)
-{
- try
- {
- zypp::Locale loc = zypp::Locale(locale->value());
-
- // add packages for the preferred locale, preserve additional locales
- zypp::ZYpp::LocaleSet lset = zypp_ptr()->getRequestedLocales();
-
- // remove the previous locale
- if (preferred_locale != zypp::Locale::noCode)
- {
- lset.erase(preferred_locale);
- }
-
- // add the new locale
- lset.insert(loc);
- zypp_ptr()->setRequestedLocales(lset);
-
- // remember the main locale
- preferred_locale = loc;
- }
- catch(...)
- {
- }
-
- return YCPVoid();
-}
-
-/**
- * @builtin SetLocale
- * @short Set The Main (Preferred) Locale -- OBSOLETED!
- * @description
- * OBSOLETED, DO NOT USE! It has been replaced by SetTextLocale() and SetMainLocale() calls (see bug #223624)
- * @param string locale Locale
- * @return void
- */
-YCPValue
-PkgModuleFunctions::SetLocale (const YCPString &locale)
-{
- y2warning("Pkg::SetLocale() is obsoleted, use Pkg::SetTextLocale() and/or Pkg::SetPackageLocale() instead. Pkg::SetLocale() currently calls both functions");
-
- SetTextLocale(locale);
- SetPackageLocale(locale);
-
- return YCPVoid();
-}
-
-/**
- * @builtin GetTextLocale
- * @short get the currently preferred locale
- * @return string locale
- * @usage Pkg::GetTextLocale() -> "en_US"
- */
-YCPValue
-PkgModuleFunctions::GetTextLocale ()
-{
- try
- {
- return YCPString(zypp_ptr()->getTextLocale().code());
- }
- catch (...)
- {
- }
-
- return YCPVoid();
-}
-
-/**
- * @builtin GetLocale
- * @short get the currently preferred locale
- * @return string locale
- * @usage Pkg::GetLocale () -> "en_US"
- */
-YCPValue
-PkgModuleFunctions::GetLocale ()
-{
- y2warning("Pkg::GetLocale() is obsoleted, use Pkg::GetTextLocale() or Pkg::GetPackageLocale() instead. Pkg::GetLocale() currently calls Pkg::GetTextLocale()");
- return GetTextLocale();
-}
-
-/**
- * @builtin GetPackageLocale
- * @short get the locale set by Pkg::SetPackageLocale() call
- * @return string locale
- * @usage Pkg::GetPackageLocale () -> "en_US"
- */
-YCPValue
-PkgModuleFunctions::GetPackageLocale ()
-{
- // the locale hasn't been initialized
- if (preferred_locale == zypp::Locale::noCode)
- {
- y2warning("The package locale hasn't been set, call Pkg::SetPackageLocale() before Pkg::GetPackageLocale()");
- }
-
- return YCPString(preferred_locale.code());
-}
-
-/**
- * @builtin SetAdditionalLocales
- *
- * @short set list of additional locales
- * @description
- * Select additional languages for installation. Call Pkg::Solve() to select the respective packages.
- * @param list<string> locales List of additional locales
- * @return void
- * @usage Pkg::SetAdditionalLocales(["de_DE"]);
- */
-YCPValue
-PkgModuleFunctions::SetAdditionalLocales (YCPList langycplist)
-{
- zypp::ZYpp::LocaleSet lset;
-
- int i = 0;
- while (i < langycplist->size())
- {
- if (langycplist->value(i)->isString())
- {
- lset.insert(zypp::Locale(langycplist->value(i)->asString()->value()));
- }
- else
- {
- y2error("Pkg::SetAdditionalLocales ([...,%s,...]) not string", langycplist->value(i)->toString().c_str());
- }
- i++;
- }
-
- // add the main locale if it's initialized
- if (preferred_locale != zypp::Locale::noCode)
- {
- lset.insert(preferred_locale);
- }
-
- try
- {
- zypp_ptr()->setRequestedLocales(lset);
- }
- catch(...)
- {
- }
-
- return YCPVoid();
-}
-
-/**
- * @builtin GetAdditionalLocales
- *
- * @short return list of additional locales
- * @return list<string>
- * @usage Pkg::GetAdditionalLocales() -> ["de_DE"];
- *
- */
-YCPValue
-PkgModuleFunctions::GetAdditionalLocales ()
-{
- YCPList langycplist;
-
- try
- {
- zypp::ZYpp::LocaleSet lset = zypp_ptr()->getRequestedLocales();
-
- for (zypp::ZYpp::LocaleSet::const_iterator it = lset.begin();
- it != lset.end(); ++it)
- {
- // ignore the main locale
- if (*it != preferred_locale)
- {
- langycplist->add (YCPString(it->code()));
- }
- }
- }
- catch(...)
- {
- }
-
- return langycplist;
-}
-
-
-/**
* @builtin LastError
*
* @short get current error as string
@@ -665,52 +260,3 @@
}
-/** ------------------------
- * Convert InstSrcDescr to product info YCPMap:
- * <TABLE>
- * <TR><TD>$[<TD>"product" <TD>: YCPString (name' 'version)
- * <TR><TD>,<TD>"vendor" <TD>: YCPString
- * <TR><TD>,<TD>"requires" <TD>: YCPString
- * <TR><TD>,<TD>"name" <TD>: YCPString
- * <TR><TD>,<TD>"version" <TD>: YCPString
- * <TR><TD>,<TD>"flags" <TD>: YCPString
- * <TR><TD>,<TD>"relnotesurl" <TD>: YCPString
- * <TR><TD>,<TD>"distproduct" <TD>: YCPString
- * <TR><TD>,<TD>"distversion" <TD>: YCPString
- * <TR><TD>,<TD>"baseproduct" <TD>: YCPString
- * <TR><TD>,<TD>"baseversion" <TD>: YCPString
- * <TR><TD>];
- * </TABLE>
-
-
-YCPMap
-PkgModuleFunctions::Descr2Map (constInstSrcDescrPtr descr)
-{
- YCPMap map;
-
- map->add (YCPString ("product"), YCPString (descr->content_product().asPkgNameEd().name.asString()
- + " "
- + descr->content_product().asPkgNameEd().edition.version()));
- map->add (YCPString ("vendor"), YCPString (descr->content_vendor()));
- map->add (YCPString ("requires"), YCPString (descr->content_requires().asString()));
-
- // for installation/modules/Product.ycp
- map->add (YCPString ("name"), YCPString (descr->content_product().asPkgNameEd().name));
- map->add (YCPString ("version"), YCPString (descr->content_product().asPkgNameEd().edition.version()));
- map->add (YCPString ("flags"), YCPString (descr->content_flags()));
- map->add (YCPString ("relnotesurl"), YCPString (descr->content_relnotesurl()));
-
- // vendor already in map
-
- map->add (YCPString ("distproduct"), YCPString (descr->content_distproduct().name));
- map->add (YCPString ("distversion"), YCPString (descr->content_distproduct().edition.version()));
-
- map->add (YCPString ("baseproduct"), YCPString (descr->content_baseproduct().asPkgNameEd().name));
- map->add (YCPString ("baseversion"), YCPString (descr->content_baseproduct().asPkgNameEd().edition.version()));
-
- map->add (YCPString ("defaultbase"), YCPString (descr->content_defaultbase()));
-
- return map;
-}
-*/
-
Modified: trunk/pkg-bindings/src/PkgModuleFunctions.h
URL: http://svn.opensuse.org/viewcvs/yast/trunk/pkg-bindings/src/PkgModuleFuncti…
==============================================================================
--- trunk/pkg-bindings/src/PkgModuleFunctions.h (original)
+++ trunk/pkg-bindings/src/PkgModuleFunctions.h Thu Dec 6 07:56:58 2007
@@ -52,6 +52,8 @@
#include <zypp/MediaSetAccess.h>
#include <zypp/ProgressData.h>
+#include <YRepo.h>
+
#include "PkgError.h"
//#include "PkgProgress.h"
class PkgProgress;
@@ -69,31 +71,6 @@
// define new _ macro
#define _(MSG) ::dgettext("pkg-bindings", MSG)
-DEFINE_PTR_TYPE(YRepo);
-class YRepo : public zypp::base::ReferenceCounted
-{
-private:
- zypp::RepoInfo _repo;
- zypp::MediaSetAccess_Ptr _maccess;
- bool _deleted;
-
- YRepo() {}
-
-public:
- YRepo(zypp::RepoInfo & repo);
- ~YRepo();
-
- const zypp::RepoInfo & repoInfo() const { return _repo; }
- zypp::RepoInfo & repoInfo() { return _repo; }
- zypp::MediaSetAccess_Ptr & mediaAccess();
-
- bool isDeleted() {return _deleted;}
- void setDeleted() {_deleted = true;}
-
-public:
- static const YRepo NOREPO;
-};
-
/**
* A simple class for package management access
*/
Added: trunk/pkg-bindings/src/PkgModuleFunctions_Register.cc
URL: http://svn.opensuse.org/viewcvs/yast/trunk/pkg-bindings/src/PkgModuleFuncti…
==============================================================================
--- trunk/pkg-bindings/src/PkgModuleFunctions_Register.cc (added)
+++ trunk/pkg-bindings/src/PkgModuleFunctions_Register.cc Thu Dec 6 07:56:58 2007
@@ -0,0 +1,9 @@
+
+#include "PkgModuleFunctions.h";
+
+void PkgModuleFunctions::registerFunctions()
+{
+#include "PkgBuiltinTable.h"
+}
+
+
Copied: trunk/pkg-bindings/src/Source_Callbacks.cc (from r42708, trunk/pkg-bindings/src/Source.cc)
URL: http://svn.opensuse.org/viewcvs/yast/trunk/pkg-bindings/src/Source_Callback…
==============================================================================
--- trunk/pkg-bindings/src/Source.cc (original)
+++ trunk/pkg-bindings/src/Source_Callbacks.cc Thu Dec 6 07:56:58 2007
@@ -1,100 +1,34 @@
-/*---------------------------------------------------------------------\
-| |
-| __ __ ____ _____ ____ |
-| \ \ / /_ _/ ___|_ _|___ \ |
-| \ V / _` \___ \ | | __) | |
-| | | (_| |___) || | / __/ |
-| |_|\__,_|____/ |_| |_____| |
-| |
-| core system |
-| (C) SuSE GmbH |
-\----------------------------------------------------------------------/
-
- File: PkgModuleFunctionsSource.cc
-
- Author: Klaus Kaempf <kkaempf(a)suse.de>
- Maintainer: Klaus Kaempf <kkaempf(a)suse.de>
-
- Summary: Access to Installation Sources
- Namespace: Pkg
- Purpose: Access to InstSrc
- Handles source related Pkg::function (list_of_arguments) calls
- from WFMInterpreter.
-/-*/
-//#include <unistd.h>
-//#include <sys/statvfs.h>
-
-#include <iostream>
-
-#include <ycpTools.h>
-#include <PkgModule.h>
-#include <PkgModuleFunctions.h>
-
-#include <Callbacks.h>
-#include <Callbacks.YCP.h>
-
-#include <zypp/Product.h>
-#include <zypp/media/MediaManager.h>
-#include <zypp/media/Mount.h>
-#include <zypp/Pathname.h>
-
-#include <zypp/RepoInfo.h>
-#include <zypp/RepoManager.h>
-#include <zypp/Fetcher.h>
-#include <zypp/repo/RepoType.h>
-#include <zypp/MediaProducts.h>
-#include <zypp/ExternalProgram.h>
-#include <zypp/ProgressData.h>
-
-#include <sstream> // ostringstream
-
-#include <PkgProgress.h>
+/* ------------------------------------------------------------------------------
+ * Copyright (c) 2007 Novell, Inc. All Rights Reserved.
+ *
+ *
+ * This program is free software; you can redistribute it and/or modify it under
+ * the terms of version 2 of the GNU General Public License as published by the
+ * Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+ * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along with
+ * this program; if not, contact Novell, Inc.
+ *
+ * To contact Novell about this file by physical or electronic mail, you may find
+ * current contact information at www.novell.com.
+ * ------------------------------------------------------------------------------
+ */
/*
- Textdomain "pkg-bindings"
+ File: $Id:$
+ Author: Ladislav Slezák <lslezak(a)novell.com>
+ Summary: Callbacks functions related to repository registration
*/
-// scanned available products
-// hack: zypp/MediaProducts.h cannot be included in PkgModuleFunctions.h
-zypp::MediaProductSet available_products;
-
-// this method should be used instead of zypp::productsInMedia()
-// it initializes the download callbacks
-void PkgModuleFunctions::ScanProductsWithCallBacks(const zypp::Url &url)
-{
- CallInitDownload(std::string(_("Scanning products in ") + url.asString()));
-
- extern ZyppRecipients::MediaChangeSensitivity _silent_probing;
- // remember the current value
- ZyppRecipients::MediaChangeSensitivity _silent_probing_old = _silent_probing;
-
- // disable media change callback for optional file
- _silent_probing = ZyppRecipients::MEDIA_CHANGE_DISABLE;
-
- y2milestone("Scanning products in %s ...", url.asString().c_str());
-
- try
- {
- available_products.clear();
- zypp::productsInMedia(url, available_products);
- }
- catch(...)
- {
- // call the final event even in case of exception
- CallDestDownload();
-
- // restore the probing flag
- _silent_probing = _silent_probing_old;
-
- // rethrow the execption
- throw;
- }
-
- CallDestDownload();
+#include <Callbacks.h>
+#include <Callbacks.YCP.h>
- // restore the probing flag
- _silent_probing = _silent_probing_old;
-}
+#include <PkgModule.h>
+#include <PkgModuleFunctions.h>
void PkgModuleFunctions::CallSourceReportStart(const std::string &text)
{
@@ -246,2695 +180,3 @@
return repotype;
}
-/**
- * Logging helper:
- * call zypp::SourceManager::sourceManager()->findSource
- * and in case of exception, log error and setLastError AND RETHROW
- */
-YRepo_Ptr PkgModuleFunctions::logFindRepository(std::vector<YRepo_Ptr>::size_type id)
-{
- try
- {
- if (id < 0 || id >= repos.size())
- {
- // not found
- throw(std::exception());
- }
-
- if (!repos[id])
- {
- // not found
- throw(std::exception());
- }
-
- if (repos[id]->isDeleted())
- {
- y2error("Source %zd has been deleted, the ID is not valid", id);
- return YRepo_Ptr();
- }
-
- return repos[id];
- }
- catch (...)
- {
- y2error("Cannot find source with ID: %zd", id);
- // TODO: improve the error message
- _last_error.setLastError(_("Cannot find source"));
- }
-
- // not found, return empty pointer
- return YRepo_Ptr();
-}
-
-long long PkgModuleFunctions::logFindAlias(const std::string &alias) const
-{
- std::vector<YRepo_Ptr>::size_type index = 0;
-
- for(std::vector<YRepo_Ptr>::const_iterator it = repos.begin(); it != repos.end() ; ++it, ++index)
- {
- if (!(*it)->isDeleted() && (*it)->repoInfo().alias() == alias)
- return index;
- }
-
- return -1LL;
-}
-
-bool PkgModuleFunctions::aliasExists(const std::string &alias) const
-{
- for(std::vector<YRepo_Ptr>::const_iterator it = repos.begin(); it != repos.end() ; ++it)
- {
- if (!(*it)->isDeleted() && (*it)->repoInfo().alias() == alias)
- return true;
- }
-
- return false;
-}
-
-/****************************************************************************************
- * @builtin SourceSetRamCache
- * @short Obsoleted function, do not use
- * @param boolean
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceSetRamCache (const YCPBoolean& a)
-{
- y2warning( "Pkg::SourceSetRamCache is obsolete and does nothing");
- return YCPBoolean( true );
-}
-
-
-/****************************************************************************************
- * @builtin SourceRestore
- *
- * @short Restore the sources from the persistent store
- * @description
- * Make sure the Source Manager is up and knows all available installation sources.
- * It's safe to call this multiple times, and once the installation sources are
- * actually enabled, it's even cheap
- *
- * @return boolean True on success
- **/
-YCPValue
-PkgModuleFunctions::SourceRestore()
-{
- if (repos.size() > 0)
- {
- y2warning("Number of registered repositories: %zd, skipping repository load!", repos.size());
- return YCPBoolean(true);
- }
-
- bool success = true;
-
- try
- {
- zypp::RepoManager repomanager = CreateRepoManager();
- std::list<zypp::RepoInfo> reps = repomanager.knownRepositories();
-
- repos.clear();
- for (std::list<zypp::RepoInfo>::iterator it = reps.begin();
- it != reps.end(); ++it)
- {
- repos.push_back(new YRepo(*it));
- }
- }
- catch (const zypp::Exception& excpt)
- {
- // FIXME: assuming the sources are already initialized
- y2error ("Error in SourceRestore: %s", excpt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- success = false;
- }
-
- return YCPBoolean(success);
-}
-
-/****************************************************************************************
- * @builtin SourceGetBrokenSources
- *
- * @short Return list of broken sources (sources which failed to restore)
- * @description
- * Get list of all sources which could not have been restored.
- * @return list<string> list of aliases (product names or URLs)
- **/
-YCPValue PkgModuleFunctions::SourceGetBrokenSources()
-{
- y2warning("Pkg::SourceGetBrokenSources() is obsoleted, it's not needed anymore.");
- return YCPList();
-}
-
-bool PkgModuleFunctions::SourceLoadReceiver(const zypp::ProgressData &progress)
-{
- y2milestone("Source Load receiver: %lld (%lld%%)", progress.val(), progress.reportValue());
-
- // get the YCP callback handler for destroy event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_ProcessProgress);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- ycp_handler->appendParameter(YCPInteger(progress.reportValue()));
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-
- return true;
-}
-
-/****************************************************************************************
- * @builtin SourceLoad
- *
- * @short Load resolvables from the installation sources
- * @description
- * Refresh the pool - Add/remove resolvables from the enabled/disabled sources.
- * @return boolean True on success
- **/
-YCPValue
-PkgModuleFunctions::SourceLoad()
-{
- std::list<std::string> stages;
- stages.push_back("Refresh Sources");
- stages.push_back("Rebuild Cache");
- stages.push_back("Load Data");
-
- PkgProgress pkgprogress(_callbackHandler);
-
- // 3 steps per repository (download, cache rebuild, load resolvables)
- pkgprogress.Start("Loading the Package Manager...", stages, "help");
-
- YCPValue ret = SourceLoadImpl(pkgprogress);
-
- pkgprogress.Done();
-
- return ret;
-}
-
-
-/****************************************************************************************
- * @builtin SourceLoad
- *
- * @short Load resolvables from the installation sources
- * @description
- * Refresh the pool - Add/remove resolvables from the enabled/disabled sources.
- * @return boolean True on success
- **/
-YCPValue
-PkgModuleFunctions::SourceLoadImpl(PkgProgress &progress)
-{
- bool success = true;
-
- int repos_to_load = 0;
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
- {
- repos_to_load++;
- }
- }
-
- // set max. value (3 steps per repository - refresh, rebuild, load)
- zypp::ProgressData prog_total(repos_to_load * 3);
- prog_total.sendTo(progress.Receiver());
-
- zypp::RepoManager repomanager = CreateRepoManager();
-
- // refresh metadata
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- // load resolvables only from enabled repos which are not deleted
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
- {
- // sub tasks
- zypp::CombinedProgressData refresh_subprogress(prog_total, 1);
-
- if (AnyResolvableFrom((*it)->repoInfo().alias()))
- {
- y2milestone("Resolvables from '%s' are already present, not loading", (*it)->repoInfo().alias().c_str());
- }
- else
- {
- // autorefresh the source
- if ((*it)->repoInfo().autorefresh())
- {
- try
- {
- y2milestone("Autorefreshing source: %s", (*it)->repoInfo().alias().c_str());
- RefreshWithCallbacks((*it)->repoInfo());
-
- zypp::ProgressData prog(1);
- prog.sendTo(refresh_subprogress);
- RefreshWithCallbacks((*it)->repoInfo());
- prog.toMax();
- }
- // NOTE: subtask progresses are reported as done in the descructor
- // no need to handle them in the exception code
- catch (const zypp::Exception& excpt)
- {
- y2error ("Error in SourceLoad: %s", excpt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- success = false;
- }
- }
- }
- }
- }
-
- progress.NextStage();
-
- // rebuild cache
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- // load resolvables only from enabled repos which are not deleted
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
- {
- // sub tasks
- zypp::CombinedProgressData rebuild_subprogress(prog_total, 1);
-
- if (AnyResolvableFrom((*it)->repoInfo().alias()))
- {
- y2milestone("Resolvables from '%s' are already present, not loading", (*it)->repoInfo().alias().c_str());
- }
- else
- {
- // autorefresh the source
- if ((*it)->repoInfo().autorefresh())
- {
- try
- {
- // rebuild cache (the default policy is "if needed")
- y2milestone("Rebuilding cache for '%s'...", (*it)->repoInfo().alias().c_str());
-
- zypp::ProgressData prog(1);
- prog.sendTo(rebuild_subprogress);
- repomanager.buildCache((*it)->repoInfo());
- prog.toMax();
- }
- // NOTE: subtask progresses are reported as done in the descructor
- // no need to handle them in the exception code
- catch (const zypp::Exception& excpt)
- {
- y2error ("Error in SourceLoad: %s", excpt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- success = false;
- }
- }
- }
- }
- }
-
- progress.NextStage();
-
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- // load resolvables only from enabled repos which are not deleted
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
- {
- // sub tasks
- zypp::CombinedProgressData load_subprogress(prog_total, 1);
-
- if (AnyResolvableFrom((*it)->repoInfo().alias()))
- {
- y2milestone("Resolvables from '%s' are already present, not loading", (*it)->repoInfo().alias().c_str());
- }
- else
- {
- zypp::ProgressData prog(1);
- prog.sendTo(load_subprogress);
-
- // load objects
- success = LoadResolvablesFrom((*it)->repoInfo()) && success;
-
- prog.toMax();
- }
- }
- }
-
- // report 100%
- prog_total.toMax();
-
- return YCPBoolean(success);
-}
-
-
-/****************************************************************************************
- * @builtin SourceStartManager
- *
- * @short Start the source manager - restore the sources and load the resolvables
- * @description
- * Calls SourceRestore(), if argument enable is true SourceLoad() is called.
- * @param boolean enable If true the resolvables are loaded from the enabled sources
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceStartManager (const YCPBoolean& enable)
-{
- PkgProgress pkgprogress(_callbackHandler);
-
- // display the progress only when 'enable' is true
- if (enable->value())
- {
- std::list<std::string> stages;
- stages.push_back("Load Sources");
- stages.push_back("Refresh Sources");
- stages.push_back("Rebuild Cache");
- stages.push_back("Load Data");
-
- // 3 steps per repository (download, cache rebuild, load resolvables)
- pkgprogress.Start("Loading the Package Manager...", stages, "help");
- }
-
- YCPValue ret = SourceStartManagerImpl(enable, pkgprogress);
-
- if (enable->value())
- {
- pkgprogress.Done();
- }
-
- return ret;
-}
-
-/****************************************************************************************
- * @builtin SourceStartManager
- *
- * @short Start the source manager - restore the sources and load the resolvables
- * @description
- * Calls SourceRestore(), if argument enable is true SourceLoad() is called.
- * @param boolean enable If true the resolvables are loaded from the enabled sources
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceStartManagerImpl(const YCPBoolean& enable, PkgProgress &progress)
-{
- YCPValue success = SourceRestore();
-
- progress.NextStage();
-
- if( enable->value() )
- {
- if (!success->asBoolean()->value())
- {
- y2warning("SourceStartManager: Some sources have not been restored, loading only the active sources...");
- }
-
- // enable all sources and load the resolvables
- success = YCPBoolean(SourceLoadImpl(progress)->asBoolean()->value() && success->asBoolean()->value());
- }
-
- return success;
-}
-
-/****************************************************************************************
- * @builtin SourceStartCache
- *
- * @short Make sure the InstSrcManager is up, and return the list of SrcIds.
- * @description
- * Make sure the InstSrcManager is up, and return the list of SrcIds.
- * In fact nothing more than:
- *
- * <code>
- * SourceStartManager( enabled_only );
- * return SourceGetCurrent( enabled_only );
- * </code>
- *
- * @param boolean enabled_only If true, make sure all InstSrces are enabled according to
- * their default, and return the Ids of enabled InstSrces only. If false, return
- * the Ids of all known InstSrces.
- *
- * @return list<integer> list of SrcIds
- **/
-YCPValue
-PkgModuleFunctions::SourceStartCache (const YCPBoolean& enabled)
-{
- try
- {
- SourceStartManager(enabled);
-
- return SourceGetCurrent(enabled);
- }
- catch (const zypp::Exception& excpt)
- {
- y2error ("Error in SourceStartCache: %s", excpt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- }
- // catch an exception from boost (e.g. a file cannot be read by non-root user)
- catch (const std::exception& err)
- {
- y2error ("Error in SourceStartCache: %s", err.what());
- _last_error.setLastError(err.what());
- }
- catch (...)
- {
- y2error("Unknown error in SourceStartCache");
- }
-
- return YCPList();
-}
-
-/****************************************************************************************
- * @builtin SourceCleanupBroken
- *
- * @short Clean up all sources that were not properly restored on the last
- * call of SourceStartManager or SourceStartCache.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceCleanupBroken ()
-{
- y2warning("Pkg::SourceCleanupBroken() is obsoleted, it's not needed anymore.");
- return YCPBoolean(true);
-}
-
-/****************************************************************************************
- * @builtin SourceGetCurrent
- *
- * @short Return the list of all InstSrc Ids.
- *
- * @param boolean enabled_only If true, or omitted, return the Ids of all enabled InstSrces.
- * If false, return the Ids of all known InstSrces.
- *
- * @return list<integer> list of SrcIds (integer)
- **/
-YCPValue
-PkgModuleFunctions::SourceGetCurrent (const YCPBoolean& enabled)
-{
- YCPList res;
-
- std::vector<YRepo_Ptr>::size_type index = 0;
- for( std::vector<YRepo_Ptr>::const_iterator it = repos.begin(); it != repos.end() ; ++it, ++index )
- {
- // ignore disabled sources if requested
- if (enabled->value())
- {
- // Note: enabled() is tribool!
- if ((*it)->repoInfo().enabled())
- {
- }
- else if (!(*it)->repoInfo().enabled())
- {
- continue;
- }
- else
- {
- continue;
- }
- }
-
- // ignore deleted sources
- if ((*it)->isDeleted())
- {
- continue;
- }
-
- res->add( YCPInteger(index) );
- }
-
- return res;
-}
-
-/****************************************************************************************
- * @builtin SourceReleaseAll
- *
- * @short Release all medias hold by all sources
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceReleaseAll ()
-{
- y2milestone("Releasing all sources...");
- bool ret = true;
-
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- try
- {
- (*it)->mediaAccess()->release();
- }
- catch (const zypp::media::MediaException & ex)
- {
- y2warning("Failed to release media for repo: %s", ex.msg().c_str());
- ret = false;
- }
- }
-
- return YCPBoolean(ret);
-}
-
-/******************************************************************************
- * @builtin SourceSaveAll
- *
- * @short Save all InstSrces.
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceSaveAll ()
-{
- y2milestone("Saving the source setup...");
-
- zypp::RepoManager repomanager = CreateRepoManager();
-
- // remove deleted repos (the old configurations) at first
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- // the repo has been removed
- if ((*it)->isDeleted())
- {
- std::string repo_alias = (*it)->repoInfo().alias();
-
- try
- {
- // remove the metadata
- zypp::RepoStatus raw_metadata_status = repomanager.metadataStatus((*it)->repoInfo());
- if (!raw_metadata_status.empty())
- {
- y2milestone("Removing metadata for source '%s'...", repo_alias.c_str());
- repomanager.cleanMetadata((*it)->repoInfo());
- }
-
- // remove the cache
- if (repomanager.isCached((*it)->repoInfo()))
- {
- y2milestone("Removing cache for '%s'...", repo_alias.c_str());
- repomanager.cleanCache((*it)->repoInfo());
- }
-
- repomanager.getRepositoryInfo(repo_alias);
- y2milestone("Removing repository '%s'", repo_alias.c_str());
- repomanager.removeRepository((*it)->repoInfo());
- }
- catch (const zypp::repo::RepoNotFoundException &ex)
- {
- // repository not found -- not critical, continue
- y2warning("No such repository: %s", repo_alias.c_str());
- }
- catch (const zypp::Exception & excpt)
- {
- y2error("Pkg::SourceSaveAll has failed: %s", excpt.msg().c_str() );
- _last_error.setLastError(ExceptionAsString(excpt));
- return YCPBoolean(false);
- }
- }
- }
-
- // save all repos (the current configuration)
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- if (!(*it)->isDeleted())
- {
- std::string current_alias = (*it)->repoInfo().alias();
-
- try
- {
- try
- {
- // if the repository already exists then just modify it
- repomanager.getRepositoryInfo(current_alias);
- y2milestone("Modifying repository '%s'", current_alias.c_str());
- repomanager.modifyRepository(current_alias, (*it)->repoInfo());
- }
- catch (const zypp::repo::RepoNotFoundException &ex)
- {
- // the repository was not found, add it
- y2milestone("Adding repository '%s'", current_alias.c_str());
- repomanager.addRepository((*it)->repoInfo());
- }
- }
- catch (zypp::Exception & excpt)
- {
- y2error("Pkg::SourceSaveAll has failed: %s", excpt.msg().c_str() );
- _last_error.setLastError(ExceptionAsString(excpt));
- return YCPBoolean(false);
- }
- }
- }
-
- y2milestone("All sources have been saved");
-
- return YCPBoolean(true);
-}
-
-/****************************************************************************************
- * @builtin SourceFinishAll
- *
- * @short Save and then disable all InstSrces.
- * @description
- * If there are no enabled sources, do nothing
- * (idempotence hack, broken design: #155459, #176013, use SourceSaveAll).
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceFinishAll ()
-{
- try
- {
- bool found_enabled = false;
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
- {
- found_enabled = true;
- break;
- }
- }
-
- if (!found_enabled)
- {
- y2milestone( "No enabled sources, skipping SourceFinishAll()" );
- return YCPBoolean( true );
- }
-
- SourceSaveAll();
-
- y2milestone( "Disabling all sources...") ;
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- (*it)->repoInfo().setEnabled(false);
- }
- // TODO FIXME remove all resolvables??
- }
- catch (zypp::Exception & excpt)
- {
- y2error("Pkg::SourceFinishAll has failed: %s", excpt.msg().c_str() );
- _last_error.setLastError(ExceptionAsString(excpt));
- return YCPBoolean(false);
- }
-
- y2milestone("All sources have been saved and disabled");
-
- return YCPBoolean(true);
-}
-
-/////////////////////////////////////////////////////////////////////////////////////////
-// Query individual sources
-/////////////////////////////////////////////////////////////////////////////////////////
-
-/****************************************************************************************
- * @builtin SourceGeneralData
- *
- * @short Get general data about the source
- * @description
- * Return general data about the source as a map:
- *
- * <code>
- * $[
- * "enabled" : YCPBoolean,
- * "autorefresh": YCPBoolean,
- * "product_dir": YCPString,
- * "type" : YCPString,
- * "url" : YCPString (without password, but see SourceURL),
- * "alias" : YCPString,
- * "name" : YCPString,
- * ];
- *
- * </code>
- * @param integer SrcId Specifies the InstSrc to query.
- * @return map
- **/
-YCPValue
-PkgModuleFunctions::SourceGeneralData (const YCPInteger& id)
-{
- YCPMap data;
-
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPVoid ();
-
- // convert type to the old strings ("YaST", "YUM" or "Plaindir")
- std::string srctype = zypp2yastType(repo->repoInfo().type().asString());
-
- data->add( YCPString("enabled"), YCPBoolean(repo->repoInfo().enabled()));
- data->add( YCPString("autorefresh"), YCPBoolean(repo->repoInfo().autorefresh()));
- data->add( YCPString("type"), YCPString(srctype));
- data->add( YCPString("product_dir"), YCPString(repo->repoInfo().path().asString()));
-
- // check if there is an URL
- if (repo->repoInfo().baseUrlsBegin() != repo->repoInfo().baseUrlsEnd())
- {
- data->add( YCPString("url"), YCPString(repo->repoInfo().baseUrlsBegin()->asString()));
- }
-
- data->add( YCPString("alias"), YCPString(repo->repoInfo().alias()));
- data->add( YCPString("name"), YCPString(repo->repoInfo().name()));
-
- YCPList base_urls;
- for( zypp::RepoInfo::urls_const_iterator it = repo->repoInfo().baseUrlsBegin(); it != repo->repoInfo().baseUrlsEnd(); ++it)
- {
- base_urls->add(YCPString(it->asString()));
- }
- data->add( YCPString("base_urls"), base_urls);
-
- data->add( YCPString("mirror_list"), YCPString(repo->repoInfo().mirrorListUrl().asString()));
-
- return data;
-}
-
-/******************************************************************************
- * @builtin SourceURL
- *
- * @short Get full source URL, including password
- * @param integer SrcId Specifies the InstSrc to query.
- * @return string or nil on failure
- **/
-YCPValue
-PkgModuleFunctions::SourceURL (const YCPInteger& id)
-{
-
- const YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPVoid();
-
- std::string url;
-
- if (repo->repoInfo().baseUrlsBegin() != repo->repoInfo().baseUrlsEnd())
- {
- // #186842
- url = repo->repoInfo().baseUrlsBegin()->asCompleteString();
- }
-
- return YCPString(url);
-}
-
-/****************************************************************************************
- * @builtin SourceMediaData
- * @short Return media data about the source
- * @description
- * Return media data about the source as a map:
- *
- * <code>
- * $["media_count": YCPInteger,
- * "media_id" : YCPString,
- * "media_vendor" : YCPString,
- * "url" : YCPString,
- * ];
- * </code>
- *
- * @param integer SrcId Specifies the InstSrc to query.
- * @return map
- **/
-YCPValue
-PkgModuleFunctions::SourceMediaData (const YCPInteger& id)
-{
- YCPMap data;
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPVoid ();
-
- std::string alias = repo->repoInfo().alias();
- bool found_resolvable = false;
- int max_medium = 1;
-
- for (zypp::ResPool::const_iterator it = zypp_ptr()->pool().begin()
- ; it != zypp_ptr()->pool().end()
- ; ++it)
- {
- if (it->resolvable()->repository().info().alias() == alias)
- {
- int medium = it->resolvable()->mediaNr();
-
- if (medium > max_medium)
- {
- max_medium = medium;
- }
- }
- }
-
- if (found_resolvable)
- {
- data->add( YCPString("media_count"), YCPInteger(max_medium));
- }
- else
- {
- y2error("No resolvable from repository '%s' found, cannot get number of media (use Pkg::SourceLoad() to load the resolvables)", alias.c_str());
- }
-
- y2warning("Pkg::SourceMediaData() doesn't return \"media_id\" and \"media_vendor\" values anymore.");
-
- // SourceMediaData returns URLs without password
- if (repo->repoInfo().baseUrlsBegin() != repo->repoInfo().baseUrlsEnd())
- {
- data->add( YCPString("url"), YCPString(repo->repoInfo().baseUrlsBegin()->asString()));
-
- // add all base URLs
- YCPList base_urls;
- for( zypp::RepoInfo::urls_const_iterator it = repo->repoInfo().baseUrlsBegin(); it != repo->repoInfo().baseUrlsEnd(); ++it)
- {
- base_urls->add(YCPString(it->asString()));
- }
- data->add( YCPString("base_urls"), base_urls);
- }
-
- return data;
-}
-
-/****************************************************************************************
- * @builtin SourceProductData
- * @short Return Product data about the source
- * @param integer SrcId Specifies the InstSrc to query.
- * @description
- * Product data about the source as a map:
- *
- * <code>
- * $[
- * "label" : YCPString,
- * "vendor" : YCPString,
- * "productname" : YCPString,
- * "productversion" : YCPString,
- * "relnotesurl" : YCPString,
- * ];
- * </code>
- *
- * @return map
- **/
-YCPValue
-PkgModuleFunctions::SourceProductData (const YCPInteger& src_id)
-{
- YCPMap ret;
-
- try
- {
- // find a product for the given source
- zypp::ResPool::byKind_iterator it = zypp_ptr()->pool().byKindBegin(zypp::ResTraits<zypp::Product>::kind);
-
- for( ; it != zypp_ptr()->pool().byKindEnd(zypp::ResTraits<zypp::Product>::kind) ; ++it)
- {
- zypp::Product::constPtr product = boost::dynamic_pointer_cast<const zypp::Product>( it->resolvable() );
-
- if( logFindAlias(product->repository().info().alias()) == src_id->value() )
- {
- ret->add( YCPString("label"), YCPString( product->summary() ) );
- ret->add( YCPString("vendor"), YCPString( product->vendor() ) );
- ret->add( YCPString("productname"), YCPString( product->name() ) );
- ret->add( YCPString("productversion"), YCPString( product->edition().version() ) );
- ret->add( YCPString("relnotesurl"), YCPString( product->releaseNotesUrl().asString()));
-
- #warning SourceProductData not finished
- /*
- data->add( YCPString("datadir"), YCPString( descr->content_datadir().asString() ) );
- TODO (?): "baseproductname", "baseproductversion", "defaultbase", "architectures",
- "requires", "linguas", "labelmap", "language", "timezone", "descrdir", "datadir"
- */
-
- break;
- }
- }
-
- if( it == zypp_ptr()->pool().byKindEnd(zypp::ResTraits<zypp::Product>::kind) )
- {
- y2error ("Product for source '%lld' not found", src_id->value());
- }
- }
- catch (...)
- {
- }
-
- return ret;
-}
-
-/****************************************************************************************
- * @builtin SourceProduct
- * @short Obsoleted function, do not use, see SourceProductData builtin
- * @deprecated
- * @param integer
- * @return map empty map
- **/
-YCPValue
-PkgModuleFunctions::SourceProduct (const YCPInteger& id)
-{
- /* TODO FIXME */
- y2error("Pkg::SourceProduct() is obsoleted, use Pkg::SourceProductData() instead!");
- return YCPMap();
-}
-
-
-YCPValue PkgModuleFunctions::SourceProvideFileCommon(const YCPInteger &id,
- const YCPInteger &mid,
- const YCPString& f,
- const YCPBoolean & optional)
-{
- CallInitDownload(std::string(_("Downloading ") + f->value()));
-
- bool found = true;
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- found = false;
-
- extern ZyppRecipients::MediaChangeSensitivity _silent_probing;
- // remember the current value
- ZyppRecipients::MediaChangeSensitivity _silent_probing_old = _silent_probing;
-
- // disable media change callback for optional file
- if (optional->value())
- _silent_probing = ZyppRecipients::MEDIA_CHANGE_OPTIONALFILE;
-
- zypp::filesystem::Pathname path; // FIXME use ManagedMedia
- if (found)
- {
- try
- {
- path = repo->mediaAccess()->provideFile(f->value(), mid->value());
- y2milestone("local path: '%s'", path.asString().c_str());
- }
- catch (const zypp::Exception& excpt)
- {
- found = false;
-
- if (!optional->value())
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2milestone("File not found: %s", f->value_cstr());
- }
- }
- }
-
- // set the original probing value
- _silent_probing = _silent_probing_old;
-
- CallDestDownload();
-
- if (found)
- {
- return YCPString(path.asString());
- }
- else
- {
- return YCPVoid();
- }
-}
-
-
-/****************************************************************************************
- * @builtin SourceProvideFile
- *
- * @short Make a file available at the local filesystem
- * @description
- * Let an InstSrc provide some file (make it available at the local filesystem).
- *
- * @param integer SrcId Specifies the InstSrc .
- * @param integer medianr Number of the media the file is located on ('1' for the 1st media).
- * @param string file Filename relative to the media root.
- *
- * @return string local path as string
- **/
-YCPValue
-PkgModuleFunctions::SourceProvideFile (const YCPInteger& id, const YCPInteger& mid, const YCPString& f)
-{
- return SourceProvideFileCommon(id, mid, f, false /*optional*/);
-}
-
-/****************************************************************************************
- * @builtin SourceProvideOptionalFile
- *
- * @short Make an optional file available at the local filesystem
- * @description
- * Let an InstSrc provide some file (make it available at the local filesystem).
- * If the file doesn't exist don't ask user for another medium and return nil
- *
- * @param integer SrcId Specifies the InstSrc .
- * @param integer medianr Number of the media the file is located on ('1' for the 1st media).
- * @param string file Filename relative to the media root.
- *
- * @return string local path as string
- **/
-YCPValue
-PkgModuleFunctions::SourceProvideOptionalFile (const YCPInteger& id, const YCPInteger& mid, const YCPString& f)
-{
- return SourceProvideFileCommon(id, mid, f, true /*optional*/);
-}
-
-/****************************************************************************************
- * @builtin SourceProvideDir
- * @short make a directory available at the local filesystem
- * @description
- * Let an InstSrc provide some directory (make it available at the local filesystem) and
- * all the files within it (non recursive).
- *
- * @param integer SrcId Specifies the InstSrc .
- * @param integer medianr Number of the media the file is located on ('1' for the 1st media).
- * @param string dir Directoryname relative to the media root.
- * @return string local path as string
- */
-YCPValue
-PkgModuleFunctions::SourceProvideDir (const YCPInteger& id, const YCPInteger& mid, const YCPString& d)
-{
- y2warning("Pkg::SourceProvideDir() is obsoleted use Pkg::SourceProvideDirectory() instead");
- // non optional, non recursive
- return SourceProvideDirectory(id, mid, d, false, false);
-}
-
-
-/****************************************************************************************
- * @builtin SourceProvideDirectory
- * @short make a directory available at the local filesystem
- * @description
- * Download a directory from repository (make it available at the local filesystem) and
- * all the files within it.
- *
- * @param integer id repository to use (id)
- * @param integer mid Number of the media where the directory is located on ('1' for the 1st media).
- * @param string d Directory name relative to the media root.
- * @param boolean optional set to true if the directory may not exist (do not report errors)
- * @param boolean recursive set to true to provide all subdirectories recursively
- * @return string local path as string or nil when an error occured
- */
-YCPValue
-PkgModuleFunctions::SourceProvideDirectory(const YCPInteger& id, const YCPInteger& mid, const YCPString& d, const YCPBoolean &optional, const YCPBoolean &recursive)
-{
- CallInitDownload(std::string(_("Downloading ") + d->value()));
-
- bool found = true;
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- found = false;
-
- zypp::filesystem::Pathname path; // FIXME user ManagedMedia
-
- extern ZyppRecipients::MediaChangeSensitivity _silent_probing;
- // remember the current value
- ZyppRecipients::MediaChangeSensitivity _silent_probing_old = _silent_probing;
-
- // disable media change callback for optional file
- if (optional->value())
- _silent_probing = ZyppRecipients::MEDIA_CHANGE_OPTIONALFILE;
-
- if (found)
- {
- try
- {
- path = repo->mediaAccess()->provideDir(d->value(), recursive->value(), mid->value());
- }
- catch (const zypp::Exception& excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2milestone ("Directory not found: %s", d->value_cstr());
- found = false;
- }
- }
-
- // set the original probing value
- _silent_probing = _silent_probing_old;
-
- CallDestDownload();
-
- if (found)
- {
- return YCPString(path.asString());
- }
- else
- {
- return YCPVoid();
- }
-}
-
-/****************************************************************************************
- * @builtin SourceChangeUrl
- * @short Change Source URL
- * @description
- * Change url of an InstSrc. Used primarely when re-starting during installation
- * and a cd-device changed from hdX to srX since ide-scsi was activated.
- * @param integer SrcId Specifies the InstSrc.
- * @param string url The new url to use.
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceChangeUrl (const YCPInteger& id, const YCPString& u)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- try
- {
- if (repo->repoInfo().baseUrlsSize() > 1)
- {
- // store current urls
- std::set<zypp::Url> baseUrls (repo->repoInfo().baseUrlsBegin(), repo->repoInfo().baseUrlsEnd());
-
- // reset url list and store the new one there
- repo->repoInfo().setBaseUrl(zypp::Url(u->value()));
-
- // add the rest of base urls
- for (std::set<zypp::Url>::const_iterator i = baseUrls.begin();
- i != baseUrls.end(); ++i)
- repo->repoInfo().addBaseUrl(*i);
- }
- else
- repo->repoInfo().setBaseUrl(zypp::Url(u->value()));
- }
- catch (const zypp::Exception & excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error ("Cannot set the new URL for source %s (%lld): %s",
- repo->repoInfo().alias().c_str(), id->asInteger()->value(), excpt.msg().c_str());
- return YCPBoolean(false);
- }
-
- return YCPBoolean(true);
-}
-
-/****************************************************************************************
- * @builtin SourceInstallOrder
- *
- * @short not implemented, do not use (Explicitly set an install order.)
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceInstallOrder (const YCPMap& ord)
-{
- /* TODO FIXME
- YCPList args;
- args->add (ord);
-
- //-------------------------------------------------------------------------------------//
- YcpArgLoad decl(__FUNCTION__);
-
- YCPMap & order_map( decl.arg<YT_MAP, YCPMap>() );
-
- if ( ! decl.load( args ) ) {
- return pkgError_bad_args;
- }
- //-------------------------------------------------------------------------------------//
-
- InstSrcManager::InstOrder order;
- order.reserve( order_map->size() );
- bool error = false;
-
- for ( YCPMapIterator it = order_map->begin(); it != order_map->end(); ++it ) {
-
- if ( it.value()->isInteger() ) {
- InstSrc::UniqueID uId( it.value()->asInteger()->value() );
- InstSrcManager::ISrcId source_id( _y2pm.instSrcManager().getSourceByID( uId ) );
- if ( source_id ) {
- if ( source_id->enabled() ) {
- order.push_back( uId ); // finaly ;)
-
- } else {
- y2error ("order map entry '%s:%s': source not enabled",
- it.key()->toString().c_str(),
- it.value()->toString().c_str() );
- error = true;
- }
- } else {
- y2error ("order map entry '%s:%s': bad source id",
- it.key()->toString().c_str(),
- it.value()->toString().c_str() );
- error = true;
- }
- } else {
- y2error ("order map entry '%s:%s': integer value expected",
- it.key()->toString().c_str(),
- it.value()->toString().c_str() );
- error = true;
- }
- }
- if ( error ) {
- return pkgError( Error::E_bad_args );
- }
-
- // store new instorder
- _y2pm.instSrcManager().setInstOrder( order );
-*/
-
-#warning SourceInstallOrder is not implemented
- return YCPBoolean( true );
-}
-
-
-static std::string timestamp ()
-{
- time_t t = time(NULL);
- struct tm * tmp = localtime(&t);
-
- if (tmp == NULL) {
- return "";
- }
-
- char outstr[50];
- if (strftime(outstr, sizeof(outstr), "%Y%m%d-%H%M%S", tmp) == 0) {
- return "";
- }
- return outstr;
-}
-
-/**
- * Take the ?alias=foo part of old_url, if any, and return it,
- * putting the rest to new_url.
- * \throws Exception on malformed URLs I guess
- */
-static std::string removeAlias (const zypp::Url & old_url,
- zypp::Url & new_url)
-{
- std::string alias;
- new_url = old_url;
- zypp::url::ParamMap query = new_url.getQueryStringMap ();
- zypp::url::ParamMap::iterator alias_it = query.find ("alias");
- if (alias_it != query.end ())
- {
- alias = alias_it->second;
- query.erase (alias_it);
- new_url.setQueryStringMap (query);
- }
- return alias;
-}
-
-std::string PkgModuleFunctions::UniqueAlias(const std::string &alias)
-{
- // make a copy
- std::string ret = alias;
-
- unsigned int id = 0;
- while(aliasExists(ret))
- {
- y2milestone("Alias %s already found: %lld", ret.c_str(), logFindAlias(ret));
-
- // the alias already exists - add a counter
- std::ostringstream ostr;
- ostr << alias << "_" << id;
-
- ret = ostr.str();
-
- y2milestone("Using alias %s", ret.c_str());
- ++id;
- }
-
- return ret;
-}
-
-
-/**
- * helper - add "mountoptions=ro" for mountable URL schemes if "mountoptions" option is not empty and
- * "rw" or "ro" option is missing
- */
-zypp::Url addRO(const zypp::Url &url)
-{
- zypp::Url ret(url);
- std::string scheme = zypp::str::toLower(url.getScheme());
-
- if (scheme == "nfs"
- || scheme == "hd"
- || scheme == "smb"
- || scheme == "iso"
- || scheme == "cd"
- || scheme == "dvd"
- )
- {
- const std::string mountoptions = "mountoptions";
- zypp::media::Mount::Options options(url.getQueryParam(mountoptions));
-
- y2debug("Current mountoptions: %s", options.asString().c_str());
-
- // if mountoptions are empty lizypp uses "ro" by default
- // don't override "rw" option from application
- // don't add "ro" if it's already present
- if (!options.empty() && !options.has("rw") && !options.has("ro"))
- {
- options["ro"];
-
- ret.setQueryParam(mountoptions, options.asString());
- y2milestone("Adding read only mount option: '%s' -> '%s'", url.asString().c_str(), ret.asString().c_str());
- }
- }
-
- return ret;
-}
-
-// helper function
-zypp::Url PkgModuleFunctions::shortenUrl(const zypp::Url &url)
-{
- std::string url_path = url.getPathName();
- std::string begin_path;
- std::string end_path;
-
- // try to convert 'http://server/dir1/dir2/dir3/dir4' -> 'http://server/dir1/.../dir4'
- std::string::size_type pos_first = url_path.find("/");
- if (pos_first == 0)
- {
- pos_first = url_path.find("/", 1);
- }
-
- if (pos_first == std::string::npos)
- {
- const int num = 5;
-
- // "/" not found use the beginning and the end part
- // 'http://server/very_long_directory_name' -> 'http://server/very_..._name'
- begin_path = std::string(url_path, 0, num);
- end_path = std::string(url_path, url_path.size() - num - 1, num);
- }
- else
- {
- unsigned int pos_last = url_path.rfind("/");
- if (pos_last == url_path.size() - 1)
- {
- pos_last = url_path.rfind("/", url_path.size() - 1);
- }
-
- if (pos_last == pos_first || pos_last < pos_first)
- {
- const int num = 5;
-
- // "/" not found use the beginning and the end part
- begin_path = std::string(url_path, 0, num);
- end_path = std::string(url_path, url_path.size() - num - 1, num);
- }
- else
- {
- begin_path = std::string(url_path, 0, pos_first + 1);
- end_path = std::string(url_path, pos_last);
- }
- }
-
- std::string new_path = begin_path + "..." + end_path;
- zypp::Url ret(url);
-
- // use the shorter path
- ret.setPathName(new_path);
- // remove query parameters
- ret.setQueryString("");
- // remove fragmet
- ret.setFragment("");
-
- y2milestone("Using shortened URL: '%s' -> '%s'", url.asString().c_str(), ret.asString().c_str());
- return ret;
-}
-
-/** Create a Source and immediately put it into the SourceManager.
- * \return the SourceId
- * \throws Exception if Source creation fails
-*/
-std::vector<zypp::RepoInfo>::size_type
-PkgModuleFunctions::createManagedSource( const zypp::Url & url_r,
- const zypp::Pathname & path_r,
- const bool base_source,
- const std::string& type,
- const std::string &alias_r )
-{
- // parse URL
- y2milestone ("Original URL: %s, product directory: %s", url_r.asString().c_str(), path_r.asString().c_str());
-
- // #158850#c17, if the URL contains an alias, we use that
- zypp::Url url;
-
- std::string alias = removeAlias(url_r, url);
- y2milestone("Alias from URL: '%s'", alias.c_str());
-
-#warning FIXME: use base_source (base_source vs. addon) (will be probably not needed)
-
- // repository type
- zypp::repo::RepoType repotype;
- zypp::RepoManager repomanager = CreateRepoManager();
-
- if (!type.empty())
- {
- try
- {
- // do conversion from the Yast type ("YaST", "YUM", "Plaindir")
- // to libzypp type ("yast", "yum", "plaindir")
- repotype = repotype.parse(yast2zyppType(type));
- }
- catch (zypp::repo::RepoUnknownTypeException &e)
- {
- y2warning("Unknown source type '%s'", type.c_str());
- }
- }
-
- // the type is not specified or is wrong, autoprobe the type
- if (repotype == zypp::repo::RepoType::NONE)
- {
- zypp::Url probe_url(url_r);
-
- if (!path_r.asString().empty())
- {
- zypp::Pathname pth(probe_url.getPathName());
- pth /= path_r;
-
- probe_url.setPathName(pth.asString());
- }
-
- y2milestone("Probing source type: '%s'", probe_url.asString().c_str());
-
- // autoprobe type of the repository
- repotype = ProbeWithCallbacks(probe_url);
- }
-
- y2milestone("Using source type: %s", repotype.asString().c_str());
-
-
- // create source definition object
- zypp::RepoInfo repo;
-
- std::string name;
-
- // set alias and name
- if (alias.empty())
- {
- // alias not set via URL, use the passed alias or the URL path
- if (alias_r.empty())
- {
- // use the last path element in URL
- std::string url_path = url.getPathName();
-
- std::string::size_type pos_begin = url_path.rfind("/");
- std::string::size_type pos_end = std::string::npos;
-
- // ignore the trailing slash
- if (pos_begin == url_path.size() - 1)
- {
- pos_begin = url_path.rfind("/", url_path.size() - 2);
-
- if (pos_begin != std::string::npos)
- {
- pos_end = url_path.size() - pos_begin - 2;
- }
- }
- else
- {
- pos_end = url_path.size() - pos_begin - 1;
- }
-
- // ignore the found slash character
- pos_begin++;
-
- alias = std::string(url_path, pos_begin, pos_end);
-
- y2milestone("Alias from URL path: %s", alias.c_str());
-
- // fallback
- if (alias.empty())
- {
- y2milestone("URL alias is empty using 'Repository'");
- alias = "Repository";
- }
- }
- else
- {
- alias = alias_r;
- }
-
- name = alias;
- }
- else
- {
- name = alias;
- }
-
-
- y2milestone("Name of the repository: '%s'", name.c_str());
-
- // alias must be unique, add a suffix if it's already used
- alias = UniqueAlias(alias);
-
- // add read only mount option to the URL if needed
- url = addRO(url);
-
- bool autorefresh = true;
-
- std::string scheme = zypp::str::toLower(url.getScheme());
- if (scheme == "cd" || scheme == "dvd")
- {
- y2milestone("Disabling autorefresh for CD/DVD repository");
- autorefresh = false;
- }
-
- repo.setAlias(alias);
- repo.setName(name);
- repo.setType(repotype);
- repo.addBaseUrl(url);
- repo.setPath(path_r);
- repo.setEnabled(true);
- repo.setAutorefresh(autorefresh);
-
- // set metadata path (#293428)
- zypp::Pathname metadatapath = repomanager.metadataPath(repo);
- repo.setMetadataPath(metadatapath);
-
- y2milestone("Adding source '%s' (%s, dir: %s)", repo.alias().c_str(), url.asString().c_str(), path_r.asString().c_str());
- // note: exceptions should be caught by the calling code
- RefreshWithCallbacks(repo);
-
- // build cache if needed
- if (!repomanager.isCached(repo))
- {
- y2milestone("Caching source '%s'...", repo.alias().c_str());
- repomanager.buildCache(repo);
- }
-
- repos.push_back(new YRepo(repo));
-
- y2milestone("Added source '%s': '%s', enabled: %s, autorefresh: %s",
- repo.alias().c_str(),
- repo.baseUrlsBegin()->asString().c_str(),
- repo.enabled() ? "true" : "false",
- repo.autorefresh() ? "true" : "false"
- );
-
- // the source is at the end of the list
- return repos.size() - 1;
-}
-
-/****************************************************************************************
- * @builtin RepositoryAdd
- *
- * @short Register a new repository
- * @description
- * Adds a new repository to the internal structures. The repository is only registered,
- * metadata is not downloaded, use Pkg::SourceRefreshNow() for that. The metadata is also loaded
- * automatically when loading the repository content (Pkg::SourceLoad())
- *
- * @param map map with repository parameters: $[ "enabled" : boolean, "autorefresh" : boolean, "name" : string,
- * "alias" : string, "base_urls" : list<string>, "prod_dir" : string, "type" : string ]
- * @return integer Repository ID or nil on error
- **/
-YCPValue PkgModuleFunctions::RepositoryAdd(const YCPMap ¶ms)
-{
- zypp::RepoInfo repo;
-
- // turn on the repo by default
- repo.setEnabled(true);
- // enable autorefresh by default
- repo.setAutorefresh(true);
-
- if (!params->value( YCPString("enabled") ).isNull() && params->value(YCPString("enabled"))->isBoolean())
- {
- repo.setEnabled(params->value(YCPString("enabled"))->asBoolean()->value());
- }
-
- if (!params->value( YCPString("autorefresh") ).isNull() && params->value(YCPString("autorefresh"))->isBoolean())
- {
- repo.setAutorefresh(params->value(YCPString("autorefresh"))->asBoolean()->value());
- }
-
- std::string alias;
-
- if (!params->value( YCPString("alias") ).isNull() && params->value(YCPString("alias"))->isString())
- {
- alias = params->value(YCPString("alias"))->asString()->value();
- }
-
- if (alias.empty())
- {
- alias = timestamp();
-
- // the alias must be unique
- alias = UniqueAlias(alias);
- }
- else
- {
- if (aliasExists(alias))
- {
- ycperror("alias %s already exists", alias.c_str());
- return YCPVoid();
- }
- }
-
- repo.setAlias(alias);
-
- // use the first base URL as a fallback name
- std::string first_url;
-
- if (!params->value( YCPString("base_urls") ).isNull() && params->value(YCPString("base_urls"))->isList())
- {
- YCPList lst(params->value(YCPString("base_urls"))->asList());
-
- for (int index = 0; index < lst->size(); ++index)
- {
- if( ! lst->value(index)->isString() )
- {
- ycperror( "Pkg::RepositoryAdd(): entry not a string at index %d: %s", index, lst->toString().c_str());
- return YCPVoid();
- }
-
- zypp::Url url;
-
- try
- {
- url = lst->value(index)->asString()->value();
- zypp::Url url_new;
-
- std::string name = removeAlias(url, url_new);
-
- if (!name.empty())
- {
- repo.setName(name);
- url = url_new;
- }
-
- // add read only mount option to the URL if needed
- url = addRO(url);
- }
- catch(const zypp::Exception & expt)
- {
- y2error("Invalid URL: %s", expt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(expt));
- return YCPVoid();
- }
-
- if (index == 0)
- {
- first_url = url.asString();
- }
-
- repo.addBaseUrl(url);
- }
- }
- else
- {
- ycperror("Missing \"base_urls\" key in the map");
- return YCPVoid();
- }
-
- // check name parameter
- if (!params->value( YCPString("name") ).isNull() && params->value(YCPString("name"))->isString())
- {
- repo.setName(params->value(YCPString("name"))->asString()->value());
- }
- else
- {
- // if the key "name" is missing and the name hasn't been set by ?alias= in the URL
- // then use the first URL as the name
- if (repo.name().empty())
- {
- repo.setName(first_url);
- }
- }
-
- if (!params->value( YCPString("type") ).isNull() && params->value(YCPString("type"))->isString())
- {
- std::string type = yast2zyppType(params->value(YCPString("type"))->asString()->value());
-
- try
- {
- zypp::repo::RepoType repotype(type);
- repo.setType(repotype);
- }
- catch (zypp::repo::RepoUnknownTypeException &e)
- {
- ycperror("Unknown source type '%s': %s", type.c_str(), e.asString().c_str());
- _last_error.setLastError(ExceptionAsString(e));
- return YCPVoid();
- }
-
- }
-
- if (!params->value( YCPString("prod_dir") ).isNull() && params->value(YCPString("prod_dir"))->isString())
- {
- repo.setPath(params->value(YCPString("prod_dir"))->asString()->value());
- }
-
- // set metadata path (#293428)
- zypp::RepoManager repomanager = CreateRepoManager();
- zypp::Pathname metadatapath = repomanager.metadataPath(repo);
- repo.setMetadataPath(metadatapath);
-
- repos.push_back(new YRepo(repo));
-
- // the new source is at the end of the list
- return YCPInteger(repos.size() - 1);
-}
-
-/****************************************************************************************
- * @builtin SourceCacheCopyTo
- *
- * @short Copy cache data of all installation sources to the target
- * @description
- * Copy cache data of all installation sources to the target located below 'dir'.
- * To be called at end of initial installation.
- *
- * @param string dir Root directory of target.
- * @return boolean true on success
- **/
-YCPValue
-PkgModuleFunctions::SourceCacheCopyTo (const YCPString& dir)
-{
- // error message (followed by detailed description)
- const std::string msg = _("Error: Cannot copy the cache to the target directory\n");
-
- std::string d = dir->value();
- y2milestone("Copying source cache to '%s'...", d.c_str());
-
- if (d.empty())
- {
- y2error("Empty parameter in Pkg::SourceCacheCopyTo()!");
- return YCPBoolean(false);
- }
-
- std::string target = d + "/var/cache";
-
- // create the target dir
- const char* argv[] =
- {
- "mkdir",
- // create parent dir
- "-p",
- // finish parameter list
- "--",
- // target
- target.c_str(),
- NULL
- };
-
- // discard stderr, no pty, stderr_fd = -1, use the default locale
- zypp::ExternalProgram prog(argv, zypp::ExternalProgram::Discard_Stderr, false, -1, true);
-
- int code = prog.close();
-
- if (code)
- {
- // error message (followed by directory name)
- _last_error.setLastError(msg + _("Cannot create directory ") + target);
- y2error("Cannot create target directory %s", target.c_str());
- return YCPBoolean(false);
- }
-
- // copy /var/cache/zypp to the target system
- const char* argv2[] =
- {
- "cp",
- // preserve time stamps
- "-a",
- // recursive
- "-r",
- // finish parameter list
- "--",
- // source
- "/var/cache/zypp",
- // target
- target.c_str(),
- NULL
- };
-
- // discard stderr, no pty, stderr_fd = -1, use the default locale
- zypp::ExternalProgram prog2(argv2, zypp::ExternalProgram::Discard_Stderr, false, -1, true);
-
- int code2 = prog2.close();
-
- if (code2)
- {
- // error message
- _last_error.setLastError(msg + _("Copying failed"));
- y2error("Cannot copy /var/cache/zypp to %s", d.c_str());
- }
-
- return YCPBoolean(!code2);
-}
-
-/****************************************************************************************
- * @builtin SourceScan
- * @short Scan a Source Media
- * @description
- * Load all InstSrces found at media_url, i.e. all sources mentioned in /media.1/products.
- * If no /media.1/products is available, InstSrc is expected to be located directly
- * below media_url (product_dir: /).
- *
- * If a product_dir is provided, only the InstSrc located at media_url/product_dir is loaded.
- *
- * In contrary to @ref SourceCreate, InstSrces are loaded into the InstSrcManager,
- * but not enabled (packages and selections are not provided to the PackageManager),
- * and the SrcIds of <b>all</b> InstSrces found are returned.
- *
- * @param string url The media to scan.
- * @optarg string product_dir Restrict scan to a certain InstSrc located in media_url/product_dir.
- *
- * @return list<integer> list of SrcIds (integer).
- **/
-YCPValue
-PkgModuleFunctions::SourceScan (const YCPString& media, const YCPString& pd)
-{
- zypp::Url url;
-
- try {
- url = zypp::Url(media->value ());
- }
- catch(const zypp::Exception & expt )
- {
- y2error ("Invalid URL: %s", expt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(expt));
- return YCPList();
- }
-
- zypp::Pathname pn(pd->value ());
-
- YCPList ids;
- std::vector<zypp::RepoInfo>::size_type id;
-
- if ( pd->value().empty() ) {
-
- // scan all sources
- zypp::MediaProductSet products;
-
- try
- {
- y2milestone("Scanning products in %s ...", url.asString().c_str());
- ScanProductsWithCallBacks(url);
- products = available_products;
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("Scanning products for '%s' has failed"
- , url.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- return ids;
- }
-
- if( products.empty() )
- {
- // no products found, use the base URL instead
- zypp::MediaProductEntry entry;
- products.insert(entry);
- }
-
- for( zypp::MediaProductSet::const_iterator it = products.begin();
- it != products.end() ; ++it )
- {
- try
- {
- y2milestone("Using product %s in directory %s", it->_name.c_str(), it->_dir.c_str());
- id = createManagedSource(url, it->_dir, false, "", it->_name);
- ids->add( YCPInteger(id) );
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("SourceScan for '%s' product '%s' has failed"
- , url.asString().c_str(), pn.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- }
- }
- } else {
- y2debug("Creating source...");
-
- try
- {
- id = createManagedSource(url, pn, false, "", "");
- ids->add( YCPInteger(id) );
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("SourceScan for '%s' product '%s' has failed"
- , url.asString().c_str(), pn.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- }
- }
-
- y2milestone("Found sources: %s", ids->toString().c_str() );
-
- return ids;
-}
-
-/****************************************************************************************
- * @builtin SourceCreate
- *
- * @short Create a Source
- * @description
- * Load and enable all InstSrces found at media_url, i.e. all sources mentioned in /media.1/products.
- * If no /media.1/products is available, InstSrc is expected to be located directly below
- * media_url (product_dir: /).
- *
- * If a product_dir is provided, only the InstSrc located at media_url/product_dir is loaded
- * and enabled.
- *
- * @param string url The media to scan.
- * @optarg string product_dir Restrict scan to a certain InstSrc located in media_url/product_dir.
- *
- * @return integer The source_id of the first InstSrc found on the media.
- **/
-YCPValue
-PkgModuleFunctions::SourceCreate (const YCPString& media, const YCPString& pd)
-{
- // not base product, autoprobe source type
- return SourceCreateEx (media, pd, false, YCPString(""));
-}
-
-YCPValue
-PkgModuleFunctions::SourceCreateBase (const YCPString& media, const YCPString& pd)
-{
- // base product, autoprobe source type
- return SourceCreateEx (media, pd, true, YCPString(""));
-}
-
-/**
- * @builtin SourceCreateType
- * @short Create source of required type
- * @description
- * Create a source without autoprobing the source type. This builtin should be used only for "Plaindir" sources, because Plaindir sources are not automatically probed in SourceCreate() builtin.
- * @param media URL of the source
- * @param pd product directory (if empty the products will be searched)
- * @param type type of the source ("YaST", "YUM" or "Plaindir")
-*/
-
-YCPValue
-PkgModuleFunctions::SourceCreateType (const YCPString& media, const YCPString& pd, const YCPString& type)
-{
- // not base product, autoprobe source type
- return SourceCreateEx (media, pd, false, type);
-}
-
-YCPValue
-PkgModuleFunctions::SourceCreateEx (const YCPString& media, const YCPString& pd, bool base, const YCPString& source_type)
-{
- y2debug("Creating source...");
-
- zypp::Pathname pn(pd->value ());
-
- zypp::Url url;
-
- try {
- url = zypp::Url(media->value ());
- }
- catch(const zypp::Exception & expt )
- {
- y2error ("Invalid URL: %s", expt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(expt));
- return YCPInteger (-1LL);
- }
-
-
- YCPList ids;
- std::vector<zypp::RepoInfo>::size_type ret = -1;
-
- const std::string type = source_type->value();
-
- if ( pd->value().empty() ) {
- // scan all sources
- zypp::MediaProductSet products;
-
- try {
- ScanProductsWithCallBacks(url);
- products = available_products;
- }
- catch ( const zypp::Exception& excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error( "Cannot read the product list from the media" );
- return YCPInteger(-1LL);
- }
-
- if( products.empty() )
- {
- // no products found, use the base URL instead
- zypp::MediaProductEntry entry ;
- products.insert( entry );
- }
-
- for( zypp::MediaProductSet::const_iterator it = products.begin();
- it != products.end() ; ++it )
- {
- try
- {
- std::vector<zypp::RepoInfo>::size_type id = createManagedSource(url, it->_dir, base, type, it->_name);
- YRepo_Ptr repo = logFindRepository(id);
-
- LoadResolvablesFrom(repo->repoInfo());
-
- // return the id of the first product
- if ( it == products.begin() )
- ret = id;
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("SourceCreate for '%s' product '%s' has failed"
- , url.asString().c_str(), pn.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- return YCPInteger(-1LL);
- }
- }
- } else {
- y2debug("Creating source...");
-
- try
- {
- ret = createManagedSource(url, pn, base, type, "");
-
- YRepo_Ptr repo = logFindRepository(ret);
- repo->repoInfo().setEnabled(true);
-
- LoadResolvablesFrom(repo->repoInfo());
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("SourceCreate for '%s' product '%s' has failed"
- , url.asString().c_str(), pn.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- }
- }
-
- PkgFreshen();
- return YCPInteger(repos.size() - 1);
-}
-
-
-/****************************************************************************************
- * @builtin SourceSetEnabled
- *
- * @short Set the default activation state of an InsrSrc.
- * @param integer SrcId Specifies the InstSrc.
- * @param boolean enabled Default activation state of source.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceSetEnabled (const YCPInteger& id, const YCPBoolean& e)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- // no change required
- bool enable = e->value();
- if ((enable && repo->repoInfo().enabled())
- || (!enable && !repo->repoInfo().enabled()))
- return YCPBoolean(true);
-
- bool success = true;
-
- try
- {
- repo->repoInfo().setEnabled(enable);
-
- // add/remove resolvables
- if (enable)
- {
- // load resolvables only when they are missing
- if (!AnyResolvableFrom(repo->repoInfo().alias()))
- {
- success = LoadResolvablesFrom(repo->repoInfo());
- }
- }
- else
- {
- // the source has been disabled, remove resolvables from the pool
- RemoveResolvablesFrom(repo->repoInfo().alias());
- }
-
- PkgFreshen();
- }
- catch (const zypp::Exception& excpt)
- {
- std::string alias = repo->repoInfo().alias();
- y2error ("Error for '%s': %s", alias.c_str(), excpt.asString().c_str());
- _last_error.setLastError(alias + ": " + ExceptionAsString(excpt));
- success = false;
- }
-
- return YCPBoolean(success);
-}
-
-/****************************************************************************************
- * @builtin SourceSetAutorefresh
- *
- * @short Set whether this source should automaticaly refresh it's
- * meta data when it gets enabled. (default true, if not CD/DVD)
- * @param integer SrcId Specifies the InstSrc.
- * @param boolean enabled Whether autorefresh should be turned on or off.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceSetAutorefresh (const YCPInteger& id, const YCPBoolean& e)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- repo->repoInfo().setAutorefresh(e->value());
-
- return YCPBoolean( true );
-}
-
-/****************************************************************************************
- * @builtin SourceFinish
- * @short Disable an Installation Source
- * @param integer SrcId Specifies the InstSrc.
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceFinish (const YCPInteger& id)
-{
- return SourceSetEnabled(id, false);
-}
-
-/****************************************************************************************
- * @builtin SourceRefreshNow
- * @short Attempt to immediately refresh a Source
- * @description
- * The InsrSrc will be encouraged to check and refresh all metadata
- * cached on disk.
- *
- * @param integer SrcId Specifies the InstSrc.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceRefreshNow (const YCPInteger& id)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- try
- {
- zypp::RepoManager repomanager = CreateRepoManager();
- y2milestone("Refreshing metadata '%s'", repo->repoInfo().alias().c_str());
- RefreshWithCallbacks(repo->repoInfo());
-
- y2milestone("Caching source '%s'...", repo->repoInfo().alias().c_str());
- repomanager.buildCache(repo->repoInfo());
- }
- catch ( const zypp::Exception & expt )
- {
- y2error ("Error while refreshing the source: %s", expt.asString().c_str());
- _last_error.setLastError(repo->repoInfo().alias() + ": " + ExceptionAsString(expt));
- return YCPBoolean(false);
- }
-
- return YCPBoolean( true );
-}
-
-/****************************************************************************************
- * @builtin SourceDelete
- * @short Delete a Source
- * @description
- * Delete an InsrSrc. The InsrSrc together with all metadata cached on disk
- * is removed. The SrcId passed becomes invalid (other SrcIds stay valid).
- *
- * @param integer SrcId Specifies the InstSrc.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceDelete (const YCPInteger& id)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- bool success = true;
-
- try
- {
- // the resolvables cannot be used anymore, remove them
- RemoveResolvablesFrom(repo->repoInfo().alias());
-
- // update 'repos'
- repo->setDeleted();
-
- PkgFreshen();
- }
- catch (const zypp::Exception& excpt)
- {
- std::string alias = repo->repoInfo().alias();
- y2error ("Error for '%s': %s", alias.c_str(), excpt.asString().c_str());
- _last_error.setLastError(alias + ": " + ExceptionAsString(excpt));
- success = false;
- }
-
- return YCPBoolean(success);
-}
-
-/****************************************************************************************
- * @builtin SourceEditGet
- *
- * @short Get state of Sources
- * @description
- * Return a list of states for all known InstSources sorted according to the
- * source priority (highest first). A source state is a map:
- * $[
- * "SrcId" : YCPInteger,
- * "enabled" : YCPBoolean
- * "autorefresh": YCPBoolean
- * ];
- *
- * @return list<map> list of source states (map)
- **/
-YCPValue
-PkgModuleFunctions::SourceEditGet ()
-{
- YCPList ret;
-
- unsigned long index = 0;
- for( std::vector<YRepo_Ptr>::const_iterator it = repos.begin(); it != repos.end(); ++it, ++index)
- {
- if (!(*it)->isDeleted())
- {
- YCPMap src_map;
-
- src_map->add(YCPString("SrcId"), YCPInteger(index));
- // Note: enabled() is tribool
- src_map->add(YCPString("enabled"), YCPBoolean((*it)->repoInfo().enabled()));
- // Note: autorefresh() is tribool
- src_map->add(YCPString("autorefresh"), YCPBoolean((*it)->repoInfo().autorefresh()));
- src_map->add(YCPString("name"), YCPString((*it)->repoInfo().name()));
-
- ret->add(src_map);
- }
- }
-
- return ret;
-}
-
-/****************************************************************************************
- * @builtin SourceEditSet
- *
- * @short Configure properties of installation sources
- * @description
- * Set states of installation sources. Note: Enabling/disabling a source does not
- * (un)load the packages from the source! Use SourceSetEnabled() if you need to refresh
- * the packages in the pool.
- *
- * @param list source_states List of source states. Same format as returned by
- * @see SourceEditGet.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceEditSet (const YCPList& states)
-{
- bool error = false;
-
- for (int index = 0; index < states->size(); index++ )
- {
- if( ! states->value(index)->isMap() )
- {
- ycperror( "Pkg::SourceEditSet, entry not a map at index %d", index);
- error = true;
- continue;
- }
-
- YCPMap descr = states->value(index)->asMap();
-
- if (descr->value( YCPString("SrcId") ).isNull() || !descr->value(YCPString("SrcId"))->isInteger())
- {
- ycperror( "Pkg::SourceEditSet, SrcId not defined for a source description at index %d", index);
- error = true;
- continue;
- }
-
- std::vector<YRepo_Ptr>::size_type id = descr->value( YCPString("SrcId") )->asInteger()->value();
-
- YRepo_Ptr repo = logFindRepository(id);
- if (!repo)
- {
- ycperror( "Pkg::SourceEditSet, source %d not found", index);
- error = true;
- continue;
- }
-
- // now, we have the source
- if( ! descr->value( YCPString("enabled")).isNull() && descr->value(YCPString("enabled"))->isBoolean ())
- {
- bool enable = descr->value(YCPString("enabled"))->asBoolean ()->value();
-
- if (repo->repoInfo().enabled() != enable)
- {
- ycpwarning("Pkg::SourceEditSet() does not refresh the pool (src: %zd, state: %s)", id, enable ? "disabled -> enabled" : "enabled -> disabled");
- }
-
- y2debug("set enabled: %d", enable);
- repo->repoInfo().setEnabled(enable);
- }
-
- if( !descr->value(YCPString("autorefresh")).isNull() && descr->value(YCPString("autorefresh"))->isBoolean ())
- {
- bool autorefresh = descr->value(YCPString("autorefresh"))->asBoolean()->value();
- y2debug("set autorefresh: %d", autorefresh);
- repo->repoInfo().setAutorefresh( autorefresh );
- }
-
- if( !descr->value(YCPString("name")).isNull() && descr->value(YCPString("name"))->isString())
- {
- // rename the source
- y2debug("set name: %s", descr->value(YCPString("name"))->asString()->value().c_str());
- repo->repoInfo().setName(descr->value(YCPString("name"))->asString()->value());
- }
-
-#warning SourceEditSet ordering not implemented yet
- }
-
- PkgFreshen();
- return YCPBoolean( !error );
-}
-
-/////////////////////////////////////////////////////////////////////////////////////////
-//
-// DEPRECATED
-//
-/////////////////////////////////////////////////////////////////////////////////////////
-
-/****************************************************************************************
- * Pkg::SourceRaisePriority (integer SrcId) -> bool
- *
- * Raise priority of source.
- *
- * @param SrcId Specifies the InstSrc.
- *
- * @return bool
- **/
-YCPValue
-PkgModuleFunctions::SourceRaisePriority (const YCPInteger& id)
-{
-#warning SourceRaisePriority is not implemented
- y2warning("SourceRaisePriority is NOT implemented");
-/* zypp::Source_Ref src;
-
- try {
- src = logFindRepository(id->value());
- }
- catch (const zypp::Exception& excpt)
- {
- return YCPBoolean(false);
- }
-
- // raise priority by one
- src.setPriority(src.priority() + 1);
-*/
-
- return YCPBoolean( true );
-
-}
-
-/****************************************************************************************
- * Pkg::SourceLowerPriority (integer SrcId) -> void
- *
- * Lower priority of source.
- *
- * @param SrcId Specifies the InstSrc.
- *
- * @return bool
- */
-YCPValue
-PkgModuleFunctions::SourceLowerPriority (const YCPInteger& id)
-{
-#warning SourceLowerPriority is not implemented
- y2warning("SourceLowerPriority is NOT implemented");
-/*
- zypp::Source_Ref src;
-
- try {
- src = logFindRepository(id->value());
- }
- catch (const zypp::Exception& excpt)
- {
- return YCPBoolean(false);
- }
-
- // lower priority by one
- src.setPriority(src.priority() - 1);
-*/
- return YCPBoolean( true );
-}
-
-/****************************************************************************************
- * Pkg::SourceSaveRanks () -> boolean
- *
- * @short Obsoleted function, do not use
- * @return boolean true
- **/
-YCPValue
-PkgModuleFunctions::SourceSaveRanks ()
-{
- y2error( "SourceSaveRanks not implemented" );
-
- return YCPBoolean( true );
-}
-
-/****************************************************************************************
- * @builtin SourceMoveDownloadArea
- *
- * @short Move download area of CURL-based sources to specified directory
- * @param path specifies the path to move the download area to
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceMoveDownloadArea (const YCPString & path)
-{
- try
- {
- y2milestone("Moving download area of all sources to %s", path->value().c_str());
- zypp::media::MediaManager manager;
- manager.setAttachPrefix(path->value());
- }
- catch (zypp::Exception & excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error("Pkg::SourceMoveDownloadArea has failed: %s", excpt.msg().c_str());
- return YCPBoolean(false);
- }
-
- y2milestone( "Download areas moved");
-
- return YCPBoolean(true);
-}
-
-/*
- * A helper function - remove all resolvables from the repository from the pool
- */
-void PkgModuleFunctions::RemoveResolvablesFrom(const std::string &alias)
-{
- // remove the resolvables if they have been loaded
- // FIXME: can be implemented better? we need a ResStore object for removing,
- // which means search for a resolvable in the pool and get the Repository
- // object which can be asked for all resolvables in it
- for (zypp::ResPool::const_iterator it = zypp_ptr()->pool().begin()
- ; it != zypp_ptr()->pool().end()
- ; ++it)
- {
- if (it->resolvable()->repository().info().alias() == alias)
- {
- y2milestone("Removing all resolvables from '%s' from the pool...", alias.c_str());
- zypp_ptr()->removeResolvables(it->resolvable()->repository().resolvables());
- break;
- }
- }
-}
-
-/*
- * A helper function - is there any resolvable from the repository in the pool?
- */
-bool PkgModuleFunctions::AnyResolvableFrom(const std::string &alias)
-{
- for (zypp::ResPool::const_iterator it = zypp_ptr()->pool().begin()
- ; it != zypp_ptr()->pool().end()
- ; ++it)
- {
- if (it->resolvable()->repository().info().alias() == alias)
- {
- return true;
- }
- }
-
- return false;
-}
-
-/*
- * A helper function - load resolvable from the repository into the pool
- * Warning: Use AnyResolvableFrom() method for checing if the resolvables might be already loaded
- */
-bool PkgModuleFunctions::LoadResolvablesFrom(const zypp::RepoInfo &repoinfo)
-{
- bool success = true;
- unsigned int size_start = zypp_ptr()->pool().size();
- y2milestone("Loading resolvables from '%s', pool size at start: %d", repoinfo.alias().c_str(), size_start);
-
- try
- {
- zypp::RepoManager repomanager = CreateRepoManager();
-
- // build cache if needed
- if (!repomanager.isCached(repoinfo))
- {
- zypp::RepoStatus raw_metadata_status = repomanager.metadataStatus(repoinfo);
- if (raw_metadata_status.empty())
- {
- y2milestone("Missing metadata for source '%s', downloading...", repoinfo.alias().c_str());
- RefreshWithCallbacks(repoinfo);
- }
-
- y2milestone("Caching source '%s'...", repoinfo.alias().c_str());
- repomanager.buildCache(repoinfo);
- }
-
- zypp::Repository repository = repomanager.createFromCache(repoinfo);
- const zypp::ResStore &store = repository.resolvables();
-
- // load resolvables
- zypp_ptr()->addResolvables(store);
-
- y2milestone("Loaded %zd resolvables", store.size());
- }
- catch(const zypp::repo::RepoNotCachedException &excpt )
- {
- std::string alias = repoinfo.alias();
- y2error ("Resolvables from '%s' havn't been loaded: %s", alias.c_str(), excpt.asString().c_str());
- _last_error.setLastError("'" + alias + "': " + ExceptionAsString(excpt));
- success = false;
-
- // FIXME ??
- /*
- // disable the source
- y2error("Disabling source %s", url.c_str());
- repo->disable();
- */
- }
- catch (const zypp::Exception& excpt)
- {
- std::string alias = repoinfo.alias();
- y2internal("Error: Loading resolvables failed: %s", ExceptionAsString(excpt).c_str());
- _last_error.setLastError("'" + alias + "': " + ExceptionAsString(excpt));
- success = false;
- }
-
- unsigned int size_end = zypp_ptr()->pool().size();
- y2milestone("Pool size at end: %d (loaded %d resolvables)", size_end, size_end - size_start);
- return success;
-}
-
-/****************************************************************************************
- * @builtin RepositoryProbe
- *
- * @short Probe type of the repository
- * @param url specifies the path to the repository
- * @param prod_dir product directory (if empty the url is probed directly)
- * @return string repository type ("NONE" if type could be determined, nil if an error occurred (e.g. resolving the hostname)
- **/
-YCPValue PkgModuleFunctions::RepositoryProbe(const YCPString& url, const YCPString& prod_dir)
-{
- y2milestone("Probing repository type: '%s'...", url->value().c_str());
- zypp::RepoManager repomanager = CreateRepoManager();
- std::string ret;
-
- try
- {
- zypp::Url probe_url(url->value());
-
- // add the product directory
- std::string prod = prod_dir->value();
-
- if (!prod.empty())
- {
- // add "/" at the begining if it's missing
- if (std::string(prod, 0, 1) != "/")
- {
- prod = "/" + prod;
- }
-
- // merge the URL path and the product path
- std::string path = probe_url.getPathName();
- path += prod;
-
- y2milestone("Using probing path: %s", path.c_str());
- probe_url.setPathName(path);
- }
-
- // add "ro" mount option
- probe_url = addRO(probe_url);
-
- // autoprobe type of the repository
- zypp::repo::RepoType repotype = ProbeWithCallbacks(probe_url);
-
- ret = zypp2yastType(repotype.asString());
- y2milestone("Detected type: '%s'...", ret.c_str());
- }
- catch (const zypp::Exception& excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error( "Cannot detect the repository type" );
- return YCPVoid();
- }
-
- return YCPString(ret);
-}
-
-/****************************************************************************************
- * @builtin RepositoryScan
- *
- * @short Scan available products in the repository
- * @param url specifies the path to the repository
- * @return list<list<string>> list of the products: [ [ <product_name_1> <directory_1> ], ...]
- **/
-YCPValue PkgModuleFunctions::RepositoryScan(const YCPString& url)
-{
- zypp::MediaProductSet products;
-
- try
- {
- zypp::Url baseurl(url->value());
-
- baseurl = addRO(baseurl);
-
- ScanProductsWithCallBacks(baseurl);
- products = available_products;
- }
- catch ( const zypp::Exception& excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error( "Cannot read the product list from the media" );
- return YCPList();
- }
-
- YCPList ret;
-
- for( zypp::MediaProductSet::const_iterator it = products.begin();
- it != products.end() ; ++it )
- {
- YCPList prod;
-
- // add product directory
- prod.add(YCPString(it->_name));
- // add product name
- prod.add(YCPString(it->_dir.asString()));
-
- ret.add(prod);
- }
-
- y2milestone("Found products: %s", ret->toString().c_str());
-
- return ret;
-}
-
-// convert libzypp type to yast strings ("YaST", "YUM" or "Plaindir")
-std::string PkgModuleFunctions::zypp2yastType(const std::string &type)
-{
- std::string ret(type);
-
- if (type_conversion_table.empty())
- {
- // initialize the conversion map
- type_conversion_table["rpm-md"] = "YUM";
- type_conversion_table["yast2"] = "YaST";
- type_conversion_table["plaindir"] = "Plaindir";
- type_conversion_table["NONE"] = "NONE";
- }
-
- std::map<std::string,std::string>::const_iterator it = type_conversion_table.find(type);
-
- // found in the conversion table
- if (it != type_conversion_table.end())
- {
- ret = it->second;
- }
- else
- {
- y2error("Cannot convert type '%s'", type.c_str());
- }
-
- return ret;
-}
-
-std::string PkgModuleFunctions::yast2zyppType(const std::string &type)
-{
- // do conversion from the Yast type ("YaST", "YUM", "Plaindir")
- // to libzypp type ("yast", "yum", "plaindir")
- // we can simply use toLower instead of a conversion table
- // in this case
- return zypp::str::toLower(type);
-}
-
Copied: trunk/pkg-bindings/src/Source_Create.cc (from r42708, trunk/pkg-bindings/src/Source.cc)
URL: http://svn.opensuse.org/viewcvs/yast/trunk/pkg-bindings/src/Source_Create.c…
==============================================================================
--- trunk/pkg-bindings/src/Source.cc (original)
+++ trunk/pkg-bindings/src/Source_Create.cc Thu Dec 6 07:56:58 2007
@@ -1,58 +1,37 @@
-/*---------------------------------------------------------------------\
-| |
-| __ __ ____ _____ ____ |
-| \ \ / /_ _/ ___|_ _|___ \ |
-| \ V / _` \___ \ | | __) | |
-| | | (_| |___) || | / __/ |
-| |_|\__,_|____/ |_| |_____| |
-| |
-| core system |
-| (C) SuSE GmbH |
-\----------------------------------------------------------------------/
-
- File: PkgModuleFunctionsSource.cc
-
- Author: Klaus Kaempf <kkaempf(a)suse.de>
- Maintainer: Klaus Kaempf <kkaempf(a)suse.de>
-
- Summary: Access to Installation Sources
- Namespace: Pkg
- Purpose: Access to InstSrc
- Handles source related Pkg::function (list_of_arguments) calls
- from WFMInterpreter.
-/-*/
-//#include <unistd.h>
-//#include <sys/statvfs.h>
-
-#include <iostream>
+/* ------------------------------------------------------------------------------
+ * Copyright (c) 2007 Novell, Inc. All Rights Reserved.
+ *
+ *
+ * This program is free software; you can redistribute it and/or modify it under
+ * the terms of version 2 of the GNU General Public License as published by the
+ * Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+ * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along with
+ * this program; if not, contact Novell, Inc.
+ *
+ * To contact Novell about this file by physical or electronic mail, you may find
+ * current contact information at www.novell.com.
+ * ------------------------------------------------------------------------------
+ */
-#include <ycpTools.h>
-#include <PkgModule.h>
-#include <PkgModuleFunctions.h>
+/*
+ File: $Id:$
+ Author: Ladislav Slezák <lslezak(a)novell.com>
+ Summary: Functions related to repository registration
+*/
#include <Callbacks.h>
#include <Callbacks.YCP.h>
-#include <zypp/Product.h>
-#include <zypp/media/MediaManager.h>
-#include <zypp/media/Mount.h>
-#include <zypp/Pathname.h>
+#include <PkgModule.h>
+#include <PkgModuleFunctions.h>
-#include <zypp/RepoInfo.h>
-#include <zypp/RepoManager.h>
-#include <zypp/Fetcher.h>
-#include <zypp/repo/RepoType.h>
#include <zypp/MediaProducts.h>
-#include <zypp/ExternalProgram.h>
-#include <zypp/ProgressData.h>
-
-#include <sstream> // ostringstream
-
-#include <PkgProgress.h>
-
-/*
- Textdomain "pkg-bindings"
-*/
+#include <zypp/media/Mount.h>
// scanned available products
// hack: zypp/MediaProducts.h cannot be included in PkgModuleFunctions.h
@@ -96,2705 +75,554 @@
_silent_probing = _silent_probing_old;
}
-void PkgModuleFunctions::CallSourceReportStart(const std::string &text)
+static std::string timestamp ()
{
- // get the YCP callback handler
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_SourceReportStart);
+ time_t t = time(NULL);
+ struct tm * tmp = localtime(&t);
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- // add parameters
- ycp_handler->appendParameter( YCPInteger(0LL) );
- ycp_handler->appendParameter( YCPString("") );
- ycp_handler->appendParameter( YCPString(text) );
- // evaluate the callback function
- ycp_handler->evaluateCall();
+ if (tmp == NULL) {
+ return "";
}
-}
-
-void PkgModuleFunctions::CallSourceReportEnd(const std::string &text)
-{
- // get the YCP callback handler for end event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_SourceReportEnd);
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- // add parameters
- ycp_handler->appendParameter( YCPInteger(0LL) );
- ycp_handler->appendParameter( YCPString("") );
- ycp_handler->appendParameter( YCPString(text) );
- ycp_handler->appendParameter( YCPString("NO_ERROR") );
- ycp_handler->appendParameter( YCPString("") );
- // evaluate the callback function
- ycp_handler->evaluateCall();
+ char outstr[50];
+ if (strftime(outstr, sizeof(outstr), "%Y%m%d-%H%M%S", tmp) == 0) {
+ return "";
}
+ return outstr;
}
-void PkgModuleFunctions::CallSourceReportInit()
+/**
+ * Take the ?alias=foo part of old_url, if any, and return it,
+ * putting the rest to new_url.
+ * \throws Exception on malformed URLs I guess
+ */
+static std::string removeAlias (const zypp::Url & old_url,
+ zypp::Url & new_url)
{
- // get the YCP callback handler for init event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_SourceReportInit);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
+ std::string alias;
+ new_url = old_url;
+ zypp::url::ParamMap query = new_url.getQueryStringMap ();
+ zypp::url::ParamMap::iterator alias_it = query.find ("alias");
+ if (alias_it != query.end ())
+ {
+ alias = alias_it->second;
+ query.erase (alias_it);
+ new_url.setQueryStringMap (query);
+ }
+ return alias;
}
-void PkgModuleFunctions::CallSourceReportDestroy()
-{
- // get the YCP callback handler for destroy event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_SourceReportDestroy);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-void PkgModuleFunctions::CallInitDownload(const std::string &task)
+/**
+ * helper - add "mountoptions=ro" for mountable URL schemes if "mountoptions" option is not empty and
+ * "rw" or "ro" option is missing
+ */
+zypp::Url addRO(const zypp::Url &url)
{
- // get the YCP callback handler for destroy event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_InitDownload);
+ zypp::Url ret(url);
+ std::string scheme = zypp::str::toLower(url.getScheme());
- // is the callback registered?
- if (ycp_handler != NULL)
+ if (scheme == "nfs"
+ || scheme == "hd"
+ || scheme == "smb"
+ || scheme == "iso"
+ || scheme == "cd"
+ || scheme == "dvd"
+ )
{
- ycp_handler->appendParameter(YCPString(task));
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-
-void PkgModuleFunctions::CallDestDownload()
-{
- // get the YCP callback handler for destroy event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_DestDownload);
+ const std::string mountoptions = "mountoptions";
+ zypp::media::Mount::Options options(url.getQueryParam(mountoptions));
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
+ y2debug("Current mountoptions: %s", options.asString().c_str());
-// this method should be used instead of RepoManager::refreshMetadata()
-void PkgModuleFunctions::RefreshWithCallbacks(const zypp::RepoInfo &repo)
-{
- CallInitDownload(std::string(_("Refreshing repository ") + repo.alias()));
+ // if mountoptions are empty lizypp uses "ro" by default
+ // don't override "rw" option from application
+ // don't add "ro" if it's already present
+ if (!options.empty() && !options.has("rw") && !options.has("ro"))
+ {
+ options["ro"];
- try
- {
- zypp::RepoManager repomanager = CreateRepoManager();
- repomanager.refreshMetadata(repo);
- }
- catch(...)
- {
- // call the final event even in case of exception
- CallDestDownload();
- // rethrow the execption
- throw;
+ ret.setQueryParam(mountoptions, options.asString());
+ y2milestone("Adding read only mount option: '%s' -> '%s'", url.asString().c_str(), ret.asString().c_str());
+ }
}
- CallDestDownload();
+ return ret;
}
-// this method should be used instead of RepoManager::probe()
-zypp::repo::RepoType PkgModuleFunctions::ProbeWithCallbacks(const zypp::Url &url)
+/** Create a Source and immediately put it into the SourceManager.
+ * \return the SourceId
+ * \throws Exception if Source creation fails
+*/
+std::vector<zypp::RepoInfo>::size_type
+PkgModuleFunctions::createManagedSource( const zypp::Url & url_r,
+ const zypp::Pathname & path_r,
+ const bool base_source,
+ const std::string& type,
+ const std::string &alias_r )
{
- CallInitDownload(std::string(_("Probing repository ") + url.asString()));
-
- zypp::repo::RepoType repotype;
-
- extern ZyppRecipients::MediaChangeSensitivity _silent_probing;
- // remember the current value
- ZyppRecipients::MediaChangeSensitivity _silent_probing_old = _silent_probing;
-
- // disable media change callback for optional file
- _silent_probing = ZyppRecipients::MEDIA_CHANGE_DISABLE;
-
- try
- {
- // probe type of the repository
- zypp::RepoManager repomanager = CreateRepoManager();
- repotype = repomanager.probe(url);
- }
- catch(...)
- {
- // call the final event even in case of exception
- CallDestDownload();
-
- // restore the probing flag
- _silent_probing = _silent_probing_old;
+ // parse URL
+ y2milestone ("Original URL: %s, product directory: %s", url_r.asString().c_str(), path_r.asString().c_str());
- // rethrow the execption
- throw;
- }
+ // #158850#c17, if the URL contains an alias, we use that
+ zypp::Url url;
- CallDestDownload();
+ std::string alias = removeAlias(url_r, url);
+ y2milestone("Alias from URL: '%s'", alias.c_str());
- // restore the probing flag
- _silent_probing = _silent_probing_old;
+#warning FIXME: use base_source (base_source vs. addon) (will be probably not needed)
- return repotype;
-}
+ // repository type
+ zypp::repo::RepoType repotype;
+ zypp::RepoManager repomanager = CreateRepoManager();
-/**
- * Logging helper:
- * call zypp::SourceManager::sourceManager()->findSource
- * and in case of exception, log error and setLastError AND RETHROW
- */
-YRepo_Ptr PkgModuleFunctions::logFindRepository(std::vector<YRepo_Ptr>::size_type id)
-{
- try
+ if (!type.empty())
{
- if (id < 0 || id >= repos.size())
+ try
{
- // not found
- throw(std::exception());
+ // do conversion from the Yast type ("YaST", "YUM", "Plaindir")
+ // to libzypp type ("yast", "yum", "plaindir")
+ repotype = repotype.parse(yast2zyppType(type));
}
-
- if (!repos[id])
+ catch (zypp::repo::RepoUnknownTypeException &e)
{
- // not found
- throw(std::exception());
+ y2warning("Unknown source type '%s'", type.c_str());
}
+ }
+
+ // the type is not specified or is wrong, autoprobe the type
+ if (repotype == zypp::repo::RepoType::NONE)
+ {
+ zypp::Url probe_url(url_r);
- if (repos[id]->isDeleted())
+ if (!path_r.asString().empty())
{
- y2error("Source %zd has been deleted, the ID is not valid", id);
- return YRepo_Ptr();
+ zypp::Pathname pth(probe_url.getPathName());
+ pth /= path_r;
+
+ probe_url.setPathName(pth.asString());
}
- return repos[id];
- }
- catch (...)
- {
- y2error("Cannot find source with ID: %zd", id);
- // TODO: improve the error message
- _last_error.setLastError(_("Cannot find source"));
+ y2milestone("Probing source type: '%s'", probe_url.asString().c_str());
+
+ // autoprobe type of the repository
+ repotype = ProbeWithCallbacks(probe_url);
}
- // not found, return empty pointer
- return YRepo_Ptr();
-}
+ y2milestone("Using source type: %s", repotype.asString().c_str());
-long long PkgModuleFunctions::logFindAlias(const std::string &alias) const
-{
- std::vector<YRepo_Ptr>::size_type index = 0;
- for(std::vector<YRepo_Ptr>::const_iterator it = repos.begin(); it != repos.end() ; ++it, ++index)
- {
- if (!(*it)->isDeleted() && (*it)->repoInfo().alias() == alias)
- return index;
- }
+ // create source definition object
+ zypp::RepoInfo repo;
- return -1LL;
-}
+ std::string name;
-bool PkgModuleFunctions::aliasExists(const std::string &alias) const
-{
- for(std::vector<YRepo_Ptr>::const_iterator it = repos.begin(); it != repos.end() ; ++it)
+ // set alias and name
+ if (alias.empty())
{
- if (!(*it)->isDeleted() && (*it)->repoInfo().alias() == alias)
- return true;
- }
+ // alias not set via URL, use the passed alias or the URL path
+ if (alias_r.empty())
+ {
+ // use the last path element in URL
+ std::string url_path = url.getPathName();
- return false;
-}
+ std::string::size_type pos_begin = url_path.rfind("/");
+ std::string::size_type pos_end = std::string::npos;
-/****************************************************************************************
- * @builtin SourceSetRamCache
- * @short Obsoleted function, do not use
- * @param boolean
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceSetRamCache (const YCPBoolean& a)
-{
- y2warning( "Pkg::SourceSetRamCache is obsolete and does nothing");
- return YCPBoolean( true );
-}
+ // ignore the trailing slash
+ if (pos_begin == url_path.size() - 1)
+ {
+ pos_begin = url_path.rfind("/", url_path.size() - 2);
+ if (pos_begin != std::string::npos)
+ {
+ pos_end = url_path.size() - pos_begin - 2;
+ }
+ }
+ else
+ {
+ pos_end = url_path.size() - pos_begin - 1;
+ }
-/****************************************************************************************
- * @builtin SourceRestore
- *
- * @short Restore the sources from the persistent store
- * @description
- * Make sure the Source Manager is up and knows all available installation sources.
- * It's safe to call this multiple times, and once the installation sources are
- * actually enabled, it's even cheap
- *
- * @return boolean True on success
- **/
-YCPValue
-PkgModuleFunctions::SourceRestore()
-{
- if (repos.size() > 0)
- {
- y2warning("Number of registered repositories: %zd, skipping repository load!", repos.size());
- return YCPBoolean(true);
- }
+ // ignore the found slash character
+ pos_begin++;
- bool success = true;
+ alias = std::string(url_path, pos_begin, pos_end);
- try
- {
- zypp::RepoManager repomanager = CreateRepoManager();
- std::list<zypp::RepoInfo> reps = repomanager.knownRepositories();
+ y2milestone("Alias from URL path: %s", alias.c_str());
- repos.clear();
- for (std::list<zypp::RepoInfo>::iterator it = reps.begin();
- it != reps.end(); ++it)
+ // fallback
+ if (alias.empty())
+ {
+ y2milestone("URL alias is empty using 'Repository'");
+ alias = "Repository";
+ }
+ }
+ else
{
- repos.push_back(new YRepo(*it));
+ alias = alias_r;
}
+
+ name = alias;
}
- catch (const zypp::Exception& excpt)
+ else
{
- // FIXME: assuming the sources are already initialized
- y2error ("Error in SourceRestore: %s", excpt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- success = false;
+ name = alias;
}
- return YCPBoolean(success);
-}
-/****************************************************************************************
- * @builtin SourceGetBrokenSources
- *
- * @short Return list of broken sources (sources which failed to restore)
- * @description
- * Get list of all sources which could not have been restored.
- * @return list<string> list of aliases (product names or URLs)
- **/
-YCPValue PkgModuleFunctions::SourceGetBrokenSources()
-{
- y2warning("Pkg::SourceGetBrokenSources() is obsoleted, it's not needed anymore.");
- return YCPList();
-}
+ y2milestone("Name of the repository: '%s'", name.c_str());
-bool PkgModuleFunctions::SourceLoadReceiver(const zypp::ProgressData &progress)
-{
- y2milestone("Source Load receiver: %lld (%lld%%)", progress.val(), progress.reportValue());
+ // alias must be unique, add a suffix if it's already used
+ alias = UniqueAlias(alias);
+
+ // add read only mount option to the URL if needed
+ url = addRO(url);
- // get the YCP callback handler for destroy event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_ProcessProgress);
+ bool autorefresh = true;
- // is the callback registered?
- if (ycp_handler != NULL)
+ std::string scheme = zypp::str::toLower(url.getScheme());
+ if (scheme == "cd" || scheme == "dvd")
{
- ycp_handler->appendParameter(YCPInteger(progress.reportValue()));
- // evaluate the callback function
- ycp_handler->evaluateCall();
+ y2milestone("Disabling autorefresh for CD/DVD repository");
+ autorefresh = false;
}
- return true;
-}
+ repo.setAlias(alias);
+ repo.setName(name);
+ repo.setType(repotype);
+ repo.addBaseUrl(url);
+ repo.setPath(path_r);
+ repo.setEnabled(true);
+ repo.setAutorefresh(autorefresh);
-/****************************************************************************************
- * @builtin SourceLoad
- *
- * @short Load resolvables from the installation sources
- * @description
- * Refresh the pool - Add/remove resolvables from the enabled/disabled sources.
- * @return boolean True on success
- **/
-YCPValue
-PkgModuleFunctions::SourceLoad()
-{
- std::list<std::string> stages;
- stages.push_back("Refresh Sources");
- stages.push_back("Rebuild Cache");
- stages.push_back("Load Data");
+ // set metadata path (#293428)
+ zypp::Pathname metadatapath = repomanager.metadataPath(repo);
+ repo.setMetadataPath(metadatapath);
- PkgProgress pkgprogress(_callbackHandler);
+ y2milestone("Adding source '%s' (%s, dir: %s)", repo.alias().c_str(), url.asString().c_str(), path_r.asString().c_str());
+ // note: exceptions should be caught by the calling code
+ RefreshWithCallbacks(repo);
- // 3 steps per repository (download, cache rebuild, load resolvables)
- pkgprogress.Start("Loading the Package Manager...", stages, "help");
+ // build cache if needed
+ if (!repomanager.isCached(repo))
+ {
+ y2milestone("Caching source '%s'...", repo.alias().c_str());
+ repomanager.buildCache(repo);
+ }
- YCPValue ret = SourceLoadImpl(pkgprogress);
+ repos.push_back(new YRepo(repo));
- pkgprogress.Done();
+ y2milestone("Added source '%s': '%s', enabled: %s, autorefresh: %s",
+ repo.alias().c_str(),
+ repo.baseUrlsBegin()->asString().c_str(),
+ repo.enabled() ? "true" : "false",
+ repo.autorefresh() ? "true" : "false"
+ );
- return ret;
+ // the source is at the end of the list
+ return repos.size() - 1;
}
-
/****************************************************************************************
- * @builtin SourceLoad
+ * @builtin RepositoryAdd
*
- * @short Load resolvables from the installation sources
+ * @short Register a new repository
* @description
- * Refresh the pool - Add/remove resolvables from the enabled/disabled sources.
- * @return boolean True on success
+ * Adds a new repository to the internal structures. The repository is only registered,
+ * metadata is not downloaded, use Pkg::SourceRefreshNow() for that. The metadata is also loaded
+ * automatically when loading the repository content (Pkg::SourceLoad())
+ *
+ * @param map map with repository parameters: $[ "enabled" : boolean, "autorefresh" : boolean, "name" : string,
+ * "alias" : string, "base_urls" : list<string>, "prod_dir" : string, "type" : string ]
+ * @return integer Repository ID or nil on error
**/
-YCPValue
-PkgModuleFunctions::SourceLoadImpl(PkgProgress &progress)
+YCPValue PkgModuleFunctions::RepositoryAdd(const YCPMap ¶ms)
{
- bool success = true;
+ zypp::RepoInfo repo;
+
+ // turn on the repo by default
+ repo.setEnabled(true);
+ // enable autorefresh by default
+ repo.setAutorefresh(true);
- int repos_to_load = 0;
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
+ if (!params->value( YCPString("enabled") ).isNull() && params->value(YCPString("enabled"))->isBoolean())
{
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
- {
- repos_to_load++;
- }
+ repo.setEnabled(params->value(YCPString("enabled"))->asBoolean()->value());
}
- // set max. value (3 steps per repository - refresh, rebuild, load)
- zypp::ProgressData prog_total(repos_to_load * 3);
- prog_total.sendTo(progress.Receiver());
+ if (!params->value( YCPString("autorefresh") ).isNull() && params->value(YCPString("autorefresh"))->isBoolean())
+ {
+ repo.setAutorefresh(params->value(YCPString("autorefresh"))->asBoolean()->value());
+ }
- zypp::RepoManager repomanager = CreateRepoManager();
+ std::string alias;
- // refresh metadata
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
+ if (!params->value( YCPString("alias") ).isNull() && params->value(YCPString("alias"))->isString())
{
- // load resolvables only from enabled repos which are not deleted
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
- {
- // sub tasks
- zypp::CombinedProgressData refresh_subprogress(prog_total, 1);
-
- if (AnyResolvableFrom((*it)->repoInfo().alias()))
- {
- y2milestone("Resolvables from '%s' are already present, not loading", (*it)->repoInfo().alias().c_str());
- }
- else
- {
- // autorefresh the source
- if ((*it)->repoInfo().autorefresh())
- {
- try
- {
- y2milestone("Autorefreshing source: %s", (*it)->repoInfo().alias().c_str());
- RefreshWithCallbacks((*it)->repoInfo());
-
- zypp::ProgressData prog(1);
- prog.sendTo(refresh_subprogress);
- RefreshWithCallbacks((*it)->repoInfo());
- prog.toMax();
- }
- // NOTE: subtask progresses are reported as done in the descructor
- // no need to handle them in the exception code
- catch (const zypp::Exception& excpt)
- {
- y2error ("Error in SourceLoad: %s", excpt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- success = false;
- }
- }
- }
- }
+ alias = params->value(YCPString("alias"))->asString()->value();
}
- progress.NextStage();
+ if (alias.empty())
+ {
+ alias = timestamp();
- // rebuild cache
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
+ // the alias must be unique
+ alias = UniqueAlias(alias);
+ }
+ else
{
- // load resolvables only from enabled repos which are not deleted
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
+ if (aliasExists(alias))
{
- // sub tasks
- zypp::CombinedProgressData rebuild_subprogress(prog_total, 1);
-
- if (AnyResolvableFrom((*it)->repoInfo().alias()))
- {
- y2milestone("Resolvables from '%s' are already present, not loading", (*it)->repoInfo().alias().c_str());
- }
- else
- {
- // autorefresh the source
- if ((*it)->repoInfo().autorefresh())
- {
- try
- {
- // rebuild cache (the default policy is "if needed")
- y2milestone("Rebuilding cache for '%s'...", (*it)->repoInfo().alias().c_str());
-
- zypp::ProgressData prog(1);
- prog.sendTo(rebuild_subprogress);
- repomanager.buildCache((*it)->repoInfo());
- prog.toMax();
- }
- // NOTE: subtask progresses are reported as done in the descructor
- // no need to handle them in the exception code
- catch (const zypp::Exception& excpt)
- {
- y2error ("Error in SourceLoad: %s", excpt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- success = false;
- }
- }
- }
+ ycperror("alias %s already exists", alias.c_str());
+ return YCPVoid();
}
}
+
+ repo.setAlias(alias);
- progress.NextStage();
+ // use the first base URL as a fallback name
+ std::string first_url;
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
+ if (!params->value( YCPString("base_urls") ).isNull() && params->value(YCPString("base_urls"))->isList())
{
- // load resolvables only from enabled repos which are not deleted
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
- {
- // sub tasks
- zypp::CombinedProgressData load_subprogress(prog_total, 1);
+ YCPList lst(params->value(YCPString("base_urls"))->asList());
- if (AnyResolvableFrom((*it)->repoInfo().alias()))
+ for (int index = 0; index < lst->size(); ++index)
+ {
+ if( ! lst->value(index)->isString() )
{
- y2milestone("Resolvables from '%s' are already present, not loading", (*it)->repoInfo().alias().c_str());
+ ycperror( "Pkg::RepositoryAdd(): entry not a string at index %d: %s", index, lst->toString().c_str());
+ return YCPVoid();
}
- else
- {
- zypp::ProgressData prog(1);
- prog.sendTo(load_subprogress);
- // load objects
- success = LoadResolvablesFrom((*it)->repoInfo()) && success;
+ zypp::Url url;
- prog.toMax();
- }
- }
- }
+ try
+ {
+ url = lst->value(index)->asString()->value();
+ zypp::Url url_new;
- // report 100%
- prog_total.toMax();
+ std::string name = removeAlias(url, url_new);
- return YCPBoolean(success);
-}
+ if (!name.empty())
+ {
+ repo.setName(name);
+ url = url_new;
+ }
+ // add read only mount option to the URL if needed
+ url = addRO(url);
+ }
+ catch(const zypp::Exception & expt)
+ {
+ y2error("Invalid URL: %s", expt.asString().c_str());
+ _last_error.setLastError(ExceptionAsString(expt));
+ return YCPVoid();
+ }
-/****************************************************************************************
- * @builtin SourceStartManager
- *
- * @short Start the source manager - restore the sources and load the resolvables
- * @description
- * Calls SourceRestore(), if argument enable is true SourceLoad() is called.
- * @param boolean enable If true the resolvables are loaded from the enabled sources
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceStartManager (const YCPBoolean& enable)
-{
- PkgProgress pkgprogress(_callbackHandler);
+ if (index == 0)
+ {
+ first_url = url.asString();
+ }
- // display the progress only when 'enable' is true
- if (enable->value())
+ repo.addBaseUrl(url);
+ }
+ }
+ else
{
- std::list<std::string> stages;
- stages.push_back("Load Sources");
- stages.push_back("Refresh Sources");
- stages.push_back("Rebuild Cache");
- stages.push_back("Load Data");
-
- // 3 steps per repository (download, cache rebuild, load resolvables)
- pkgprogress.Start("Loading the Package Manager...", stages, "help");
+ ycperror("Missing \"base_urls\" key in the map");
+ return YCPVoid();
}
- YCPValue ret = SourceStartManagerImpl(enable, pkgprogress);
-
- if (enable->value())
+ // check name parameter
+ if (!params->value( YCPString("name") ).isNull() && params->value(YCPString("name"))->isString())
{
- pkgprogress.Done();
+ repo.setName(params->value(YCPString("name"))->asString()->value());
}
-
- return ret;
-}
-
-/****************************************************************************************
- * @builtin SourceStartManager
- *
- * @short Start the source manager - restore the sources and load the resolvables
- * @description
- * Calls SourceRestore(), if argument enable is true SourceLoad() is called.
- * @param boolean enable If true the resolvables are loaded from the enabled sources
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceStartManagerImpl(const YCPBoolean& enable, PkgProgress &progress)
-{
- YCPValue success = SourceRestore();
-
- progress.NextStage();
-
- if( enable->value() )
+ else
{
- if (!success->asBoolean()->value())
+ // if the key "name" is missing and the name hasn't been set by ?alias= in the URL
+ // then use the first URL as the name
+ if (repo.name().empty())
{
- y2warning("SourceStartManager: Some sources have not been restored, loading only the active sources...");
+ repo.setName(first_url);
}
-
- // enable all sources and load the resolvables
- success = YCPBoolean(SourceLoadImpl(progress)->asBoolean()->value() && success->asBoolean()->value());
}
- return success;
-}
-
-/****************************************************************************************
- * @builtin SourceStartCache
- *
- * @short Make sure the InstSrcManager is up, and return the list of SrcIds.
- * @description
- * Make sure the InstSrcManager is up, and return the list of SrcIds.
- * In fact nothing more than:
- *
- * <code>
- * SourceStartManager( enabled_only );
- * return SourceGetCurrent( enabled_only );
- * </code>
- *
- * @param boolean enabled_only If true, make sure all InstSrces are enabled according to
- * their default, and return the Ids of enabled InstSrces only. If false, return
- * the Ids of all known InstSrces.
- *
- * @return list<integer> list of SrcIds
- **/
-YCPValue
-PkgModuleFunctions::SourceStartCache (const YCPBoolean& enabled)
-{
- try
+ if (!params->value( YCPString("type") ).isNull() && params->value(YCPString("type"))->isString())
{
- SourceStartManager(enabled);
+ std::string type = yast2zyppType(params->value(YCPString("type"))->asString()->value());
+
+ try
+ {
+ zypp::repo::RepoType repotype(type);
+ repo.setType(repotype);
+ }
+ catch (zypp::repo::RepoUnknownTypeException &e)
+ {
+ ycperror("Unknown source type '%s': %s", type.c_str(), e.asString().c_str());
+ _last_error.setLastError(ExceptionAsString(e));
+ return YCPVoid();
+ }
- return SourceGetCurrent(enabled);
- }
- catch (const zypp::Exception& excpt)
- {
- y2error ("Error in SourceStartCache: %s", excpt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- }
- // catch an exception from boost (e.g. a file cannot be read by non-root user)
- catch (const std::exception& err)
- {
- y2error ("Error in SourceStartCache: %s", err.what());
- _last_error.setLastError(err.what());
}
- catch (...)
+
+ if (!params->value( YCPString("prod_dir") ).isNull() && params->value(YCPString("prod_dir"))->isString())
{
- y2error("Unknown error in SourceStartCache");
+ repo.setPath(params->value(YCPString("prod_dir"))->asString()->value());
}
- return YCPList();
-}
+ // set metadata path (#293428)
+ zypp::RepoManager repomanager = CreateRepoManager();
+ zypp::Pathname metadatapath = repomanager.metadataPath(repo);
+ repo.setMetadataPath(metadatapath);
-/****************************************************************************************
- * @builtin SourceCleanupBroken
- *
- * @short Clean up all sources that were not properly restored on the last
- * call of SourceStartManager or SourceStartCache.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceCleanupBroken ()
-{
- y2warning("Pkg::SourceCleanupBroken() is obsoleted, it's not needed anymore.");
- return YCPBoolean(true);
+ repos.push_back(new YRepo(repo));
+
+ // the new source is at the end of the list
+ return YCPInteger(repos.size() - 1);
}
/****************************************************************************************
- * @builtin SourceGetCurrent
+ * @builtin SourceCreate
*
- * @short Return the list of all InstSrc Ids.
+ * @short Create a Source
+ * @description
+ * Load and enable all InstSrces found at media_url, i.e. all sources mentioned in /media.1/products.
+ * If no /media.1/products is available, InstSrc is expected to be located directly below
+ * media_url (product_dir: /).
*
- * @param boolean enabled_only If true, or omitted, return the Ids of all enabled InstSrces.
- * If false, return the Ids of all known InstSrces.
+ * If a product_dir is provided, only the InstSrc located at media_url/product_dir is loaded
+ * and enabled.
*
- * @return list<integer> list of SrcIds (integer)
- **/
-YCPValue
-PkgModuleFunctions::SourceGetCurrent (const YCPBoolean& enabled)
-{
- YCPList res;
-
- std::vector<YRepo_Ptr>::size_type index = 0;
- for( std::vector<YRepo_Ptr>::const_iterator it = repos.begin(); it != repos.end() ; ++it, ++index )
- {
- // ignore disabled sources if requested
- if (enabled->value())
- {
- // Note: enabled() is tribool!
- if ((*it)->repoInfo().enabled())
- {
- }
- else if (!(*it)->repoInfo().enabled())
- {
- continue;
- }
- else
- {
- continue;
- }
- }
-
- // ignore deleted sources
- if ((*it)->isDeleted())
- {
- continue;
- }
-
- res->add( YCPInteger(index) );
- }
-
- return res;
-}
-
-/****************************************************************************************
- * @builtin SourceReleaseAll
- *
- * @short Release all medias hold by all sources
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceReleaseAll ()
-{
- y2milestone("Releasing all sources...");
- bool ret = true;
-
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- try
- {
- (*it)->mediaAccess()->release();
- }
- catch (const zypp::media::MediaException & ex)
- {
- y2warning("Failed to release media for repo: %s", ex.msg().c_str());
- ret = false;
- }
- }
-
- return YCPBoolean(ret);
-}
-
-/******************************************************************************
- * @builtin SourceSaveAll
- *
- * @short Save all InstSrces.
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceSaveAll ()
-{
- y2milestone("Saving the source setup...");
-
- zypp::RepoManager repomanager = CreateRepoManager();
-
- // remove deleted repos (the old configurations) at first
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- // the repo has been removed
- if ((*it)->isDeleted())
- {
- std::string repo_alias = (*it)->repoInfo().alias();
-
- try
- {
- // remove the metadata
- zypp::RepoStatus raw_metadata_status = repomanager.metadataStatus((*it)->repoInfo());
- if (!raw_metadata_status.empty())
- {
- y2milestone("Removing metadata for source '%s'...", repo_alias.c_str());
- repomanager.cleanMetadata((*it)->repoInfo());
- }
-
- // remove the cache
- if (repomanager.isCached((*it)->repoInfo()))
- {
- y2milestone("Removing cache for '%s'...", repo_alias.c_str());
- repomanager.cleanCache((*it)->repoInfo());
- }
-
- repomanager.getRepositoryInfo(repo_alias);
- y2milestone("Removing repository '%s'", repo_alias.c_str());
- repomanager.removeRepository((*it)->repoInfo());
- }
- catch (const zypp::repo::RepoNotFoundException &ex)
- {
- // repository not found -- not critical, continue
- y2warning("No such repository: %s", repo_alias.c_str());
- }
- catch (const zypp::Exception & excpt)
- {
- y2error("Pkg::SourceSaveAll has failed: %s", excpt.msg().c_str() );
- _last_error.setLastError(ExceptionAsString(excpt));
- return YCPBoolean(false);
- }
- }
- }
-
- // save all repos (the current configuration)
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- if (!(*it)->isDeleted())
- {
- std::string current_alias = (*it)->repoInfo().alias();
-
- try
- {
- try
- {
- // if the repository already exists then just modify it
- repomanager.getRepositoryInfo(current_alias);
- y2milestone("Modifying repository '%s'", current_alias.c_str());
- repomanager.modifyRepository(current_alias, (*it)->repoInfo());
- }
- catch (const zypp::repo::RepoNotFoundException &ex)
- {
- // the repository was not found, add it
- y2milestone("Adding repository '%s'", current_alias.c_str());
- repomanager.addRepository((*it)->repoInfo());
- }
- }
- catch (zypp::Exception & excpt)
- {
- y2error("Pkg::SourceSaveAll has failed: %s", excpt.msg().c_str() );
- _last_error.setLastError(ExceptionAsString(excpt));
- return YCPBoolean(false);
- }
- }
- }
-
- y2milestone("All sources have been saved");
-
- return YCPBoolean(true);
-}
-
-/****************************************************************************************
- * @builtin SourceFinishAll
- *
- * @short Save and then disable all InstSrces.
- * @description
- * If there are no enabled sources, do nothing
- * (idempotence hack, broken design: #155459, #176013, use SourceSaveAll).
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceFinishAll ()
-{
- try
- {
- bool found_enabled = false;
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
- {
- found_enabled = true;
- break;
- }
- }
-
- if (!found_enabled)
- {
- y2milestone( "No enabled sources, skipping SourceFinishAll()" );
- return YCPBoolean( true );
- }
-
- SourceSaveAll();
-
- y2milestone( "Disabling all sources...") ;
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- (*it)->repoInfo().setEnabled(false);
- }
- // TODO FIXME remove all resolvables??
- }
- catch (zypp::Exception & excpt)
- {
- y2error("Pkg::SourceFinishAll has failed: %s", excpt.msg().c_str() );
- _last_error.setLastError(ExceptionAsString(excpt));
- return YCPBoolean(false);
- }
-
- y2milestone("All sources have been saved and disabled");
-
- return YCPBoolean(true);
-}
-
-/////////////////////////////////////////////////////////////////////////////////////////
-// Query individual sources
-/////////////////////////////////////////////////////////////////////////////////////////
-
-/****************************************************************************************
- * @builtin SourceGeneralData
- *
- * @short Get general data about the source
- * @description
- * Return general data about the source as a map:
- *
- * <code>
- * $[
- * "enabled" : YCPBoolean,
- * "autorefresh": YCPBoolean,
- * "product_dir": YCPString,
- * "type" : YCPString,
- * "url" : YCPString (without password, but see SourceURL),
- * "alias" : YCPString,
- * "name" : YCPString,
- * ];
- *
- * </code>
- * @param integer SrcId Specifies the InstSrc to query.
- * @return map
- **/
-YCPValue
-PkgModuleFunctions::SourceGeneralData (const YCPInteger& id)
-{
- YCPMap data;
-
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPVoid ();
-
- // convert type to the old strings ("YaST", "YUM" or "Plaindir")
- std::string srctype = zypp2yastType(repo->repoInfo().type().asString());
-
- data->add( YCPString("enabled"), YCPBoolean(repo->repoInfo().enabled()));
- data->add( YCPString("autorefresh"), YCPBoolean(repo->repoInfo().autorefresh()));
- data->add( YCPString("type"), YCPString(srctype));
- data->add( YCPString("product_dir"), YCPString(repo->repoInfo().path().asString()));
-
- // check if there is an URL
- if (repo->repoInfo().baseUrlsBegin() != repo->repoInfo().baseUrlsEnd())
- {
- data->add( YCPString("url"), YCPString(repo->repoInfo().baseUrlsBegin()->asString()));
- }
-
- data->add( YCPString("alias"), YCPString(repo->repoInfo().alias()));
- data->add( YCPString("name"), YCPString(repo->repoInfo().name()));
-
- YCPList base_urls;
- for( zypp::RepoInfo::urls_const_iterator it = repo->repoInfo().baseUrlsBegin(); it != repo->repoInfo().baseUrlsEnd(); ++it)
- {
- base_urls->add(YCPString(it->asString()));
- }
- data->add( YCPString("base_urls"), base_urls);
-
- data->add( YCPString("mirror_list"), YCPString(repo->repoInfo().mirrorListUrl().asString()));
-
- return data;
-}
-
-/******************************************************************************
- * @builtin SourceURL
- *
- * @short Get full source URL, including password
- * @param integer SrcId Specifies the InstSrc to query.
- * @return string or nil on failure
- **/
-YCPValue
-PkgModuleFunctions::SourceURL (const YCPInteger& id)
-{
-
- const YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPVoid();
-
- std::string url;
-
- if (repo->repoInfo().baseUrlsBegin() != repo->repoInfo().baseUrlsEnd())
- {
- // #186842
- url = repo->repoInfo().baseUrlsBegin()->asCompleteString();
- }
-
- return YCPString(url);
-}
-
-/****************************************************************************************
- * @builtin SourceMediaData
- * @short Return media data about the source
- * @description
- * Return media data about the source as a map:
- *
- * <code>
- * $["media_count": YCPInteger,
- * "media_id" : YCPString,
- * "media_vendor" : YCPString,
- * "url" : YCPString,
- * ];
- * </code>
- *
- * @param integer SrcId Specifies the InstSrc to query.
- * @return map
- **/
-YCPValue
-PkgModuleFunctions::SourceMediaData (const YCPInteger& id)
-{
- YCPMap data;
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPVoid ();
-
- std::string alias = repo->repoInfo().alias();
- bool found_resolvable = false;
- int max_medium = 1;
-
- for (zypp::ResPool::const_iterator it = zypp_ptr()->pool().begin()
- ; it != zypp_ptr()->pool().end()
- ; ++it)
- {
- if (it->resolvable()->repository().info().alias() == alias)
- {
- int medium = it->resolvable()->mediaNr();
-
- if (medium > max_medium)
- {
- max_medium = medium;
- }
- }
- }
-
- if (found_resolvable)
- {
- data->add( YCPString("media_count"), YCPInteger(max_medium));
- }
- else
- {
- y2error("No resolvable from repository '%s' found, cannot get number of media (use Pkg::SourceLoad() to load the resolvables)", alias.c_str());
- }
-
- y2warning("Pkg::SourceMediaData() doesn't return \"media_id\" and \"media_vendor\" values anymore.");
-
- // SourceMediaData returns URLs without password
- if (repo->repoInfo().baseUrlsBegin() != repo->repoInfo().baseUrlsEnd())
- {
- data->add( YCPString("url"), YCPString(repo->repoInfo().baseUrlsBegin()->asString()));
-
- // add all base URLs
- YCPList base_urls;
- for( zypp::RepoInfo::urls_const_iterator it = repo->repoInfo().baseUrlsBegin(); it != repo->repoInfo().baseUrlsEnd(); ++it)
- {
- base_urls->add(YCPString(it->asString()));
- }
- data->add( YCPString("base_urls"), base_urls);
- }
-
- return data;
-}
-
-/****************************************************************************************
- * @builtin SourceProductData
- * @short Return Product data about the source
- * @param integer SrcId Specifies the InstSrc to query.
- * @description
- * Product data about the source as a map:
- *
- * <code>
- * $[
- * "label" : YCPString,
- * "vendor" : YCPString,
- * "productname" : YCPString,
- * "productversion" : YCPString,
- * "relnotesurl" : YCPString,
- * ];
- * </code>
- *
- * @return map
- **/
-YCPValue
-PkgModuleFunctions::SourceProductData (const YCPInteger& src_id)
-{
- YCPMap ret;
-
- try
- {
- // find a product for the given source
- zypp::ResPool::byKind_iterator it = zypp_ptr()->pool().byKindBegin(zypp::ResTraits<zypp::Product>::kind);
-
- for( ; it != zypp_ptr()->pool().byKindEnd(zypp::ResTraits<zypp::Product>::kind) ; ++it)
- {
- zypp::Product::constPtr product = boost::dynamic_pointer_cast<const zypp::Product>( it->resolvable() );
-
- if( logFindAlias(product->repository().info().alias()) == src_id->value() )
- {
- ret->add( YCPString("label"), YCPString( product->summary() ) );
- ret->add( YCPString("vendor"), YCPString( product->vendor() ) );
- ret->add( YCPString("productname"), YCPString( product->name() ) );
- ret->add( YCPString("productversion"), YCPString( product->edition().version() ) );
- ret->add( YCPString("relnotesurl"), YCPString( product->releaseNotesUrl().asString()));
-
- #warning SourceProductData not finished
- /*
- data->add( YCPString("datadir"), YCPString( descr->content_datadir().asString() ) );
- TODO (?): "baseproductname", "baseproductversion", "defaultbase", "architectures",
- "requires", "linguas", "labelmap", "language", "timezone", "descrdir", "datadir"
- */
-
- break;
- }
- }
-
- if( it == zypp_ptr()->pool().byKindEnd(zypp::ResTraits<zypp::Product>::kind) )
- {
- y2error ("Product for source '%lld' not found", src_id->value());
- }
- }
- catch (...)
- {
- }
-
- return ret;
-}
-
-/****************************************************************************************
- * @builtin SourceProduct
- * @short Obsoleted function, do not use, see SourceProductData builtin
- * @deprecated
- * @param integer
- * @return map empty map
- **/
-YCPValue
-PkgModuleFunctions::SourceProduct (const YCPInteger& id)
-{
- /* TODO FIXME */
- y2error("Pkg::SourceProduct() is obsoleted, use Pkg::SourceProductData() instead!");
- return YCPMap();
-}
-
-
-YCPValue PkgModuleFunctions::SourceProvideFileCommon(const YCPInteger &id,
- const YCPInteger &mid,
- const YCPString& f,
- const YCPBoolean & optional)
-{
- CallInitDownload(std::string(_("Downloading ") + f->value()));
-
- bool found = true;
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- found = false;
-
- extern ZyppRecipients::MediaChangeSensitivity _silent_probing;
- // remember the current value
- ZyppRecipients::MediaChangeSensitivity _silent_probing_old = _silent_probing;
-
- // disable media change callback for optional file
- if (optional->value())
- _silent_probing = ZyppRecipients::MEDIA_CHANGE_OPTIONALFILE;
-
- zypp::filesystem::Pathname path; // FIXME use ManagedMedia
- if (found)
- {
- try
- {
- path = repo->mediaAccess()->provideFile(f->value(), mid->value());
- y2milestone("local path: '%s'", path.asString().c_str());
- }
- catch (const zypp::Exception& excpt)
- {
- found = false;
-
- if (!optional->value())
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2milestone("File not found: %s", f->value_cstr());
- }
- }
- }
-
- // set the original probing value
- _silent_probing = _silent_probing_old;
-
- CallDestDownload();
-
- if (found)
- {
- return YCPString(path.asString());
- }
- else
- {
- return YCPVoid();
- }
-}
-
-
-/****************************************************************************************
- * @builtin SourceProvideFile
- *
- * @short Make a file available at the local filesystem
- * @description
- * Let an InstSrc provide some file (make it available at the local filesystem).
- *
- * @param integer SrcId Specifies the InstSrc .
- * @param integer medianr Number of the media the file is located on ('1' for the 1st media).
- * @param string file Filename relative to the media root.
- *
- * @return string local path as string
- **/
-YCPValue
-PkgModuleFunctions::SourceProvideFile (const YCPInteger& id, const YCPInteger& mid, const YCPString& f)
-{
- return SourceProvideFileCommon(id, mid, f, false /*optional*/);
-}
-
-/****************************************************************************************
- * @builtin SourceProvideOptionalFile
- *
- * @short Make an optional file available at the local filesystem
- * @description
- * Let an InstSrc provide some file (make it available at the local filesystem).
- * If the file doesn't exist don't ask user for another medium and return nil
- *
- * @param integer SrcId Specifies the InstSrc .
- * @param integer medianr Number of the media the file is located on ('1' for the 1st media).
- * @param string file Filename relative to the media root.
- *
- * @return string local path as string
- **/
-YCPValue
-PkgModuleFunctions::SourceProvideOptionalFile (const YCPInteger& id, const YCPInteger& mid, const YCPString& f)
-{
- return SourceProvideFileCommon(id, mid, f, true /*optional*/);
-}
-
-/****************************************************************************************
- * @builtin SourceProvideDir
- * @short make a directory available at the local filesystem
- * @description
- * Let an InstSrc provide some directory (make it available at the local filesystem) and
- * all the files within it (non recursive).
- *
- * @param integer SrcId Specifies the InstSrc .
- * @param integer medianr Number of the media the file is located on ('1' for the 1st media).
- * @param string dir Directoryname relative to the media root.
- * @return string local path as string
- */
-YCPValue
-PkgModuleFunctions::SourceProvideDir (const YCPInteger& id, const YCPInteger& mid, const YCPString& d)
-{
- y2warning("Pkg::SourceProvideDir() is obsoleted use Pkg::SourceProvideDirectory() instead");
- // non optional, non recursive
- return SourceProvideDirectory(id, mid, d, false, false);
-}
-
-
-/****************************************************************************************
- * @builtin SourceProvideDirectory
- * @short make a directory available at the local filesystem
- * @description
- * Download a directory from repository (make it available at the local filesystem) and
- * all the files within it.
- *
- * @param integer id repository to use (id)
- * @param integer mid Number of the media where the directory is located on ('1' for the 1st media).
- * @param string d Directory name relative to the media root.
- * @param boolean optional set to true if the directory may not exist (do not report errors)
- * @param boolean recursive set to true to provide all subdirectories recursively
- * @return string local path as string or nil when an error occured
- */
-YCPValue
-PkgModuleFunctions::SourceProvideDirectory(const YCPInteger& id, const YCPInteger& mid, const YCPString& d, const YCPBoolean &optional, const YCPBoolean &recursive)
-{
- CallInitDownload(std::string(_("Downloading ") + d->value()));
-
- bool found = true;
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- found = false;
-
- zypp::filesystem::Pathname path; // FIXME user ManagedMedia
-
- extern ZyppRecipients::MediaChangeSensitivity _silent_probing;
- // remember the current value
- ZyppRecipients::MediaChangeSensitivity _silent_probing_old = _silent_probing;
-
- // disable media change callback for optional file
- if (optional->value())
- _silent_probing = ZyppRecipients::MEDIA_CHANGE_OPTIONALFILE;
-
- if (found)
- {
- try
- {
- path = repo->mediaAccess()->provideDir(d->value(), recursive->value(), mid->value());
- }
- catch (const zypp::Exception& excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2milestone ("Directory not found: %s", d->value_cstr());
- found = false;
- }
- }
-
- // set the original probing value
- _silent_probing = _silent_probing_old;
-
- CallDestDownload();
-
- if (found)
- {
- return YCPString(path.asString());
- }
- else
- {
- return YCPVoid();
- }
-}
-
-/****************************************************************************************
- * @builtin SourceChangeUrl
- * @short Change Source URL
- * @description
- * Change url of an InstSrc. Used primarely when re-starting during installation
- * and a cd-device changed from hdX to srX since ide-scsi was activated.
- * @param integer SrcId Specifies the InstSrc.
- * @param string url The new url to use.
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceChangeUrl (const YCPInteger& id, const YCPString& u)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- try
- {
- if (repo->repoInfo().baseUrlsSize() > 1)
- {
- // store current urls
- std::set<zypp::Url> baseUrls (repo->repoInfo().baseUrlsBegin(), repo->repoInfo().baseUrlsEnd());
-
- // reset url list and store the new one there
- repo->repoInfo().setBaseUrl(zypp::Url(u->value()));
-
- // add the rest of base urls
- for (std::set<zypp::Url>::const_iterator i = baseUrls.begin();
- i != baseUrls.end(); ++i)
- repo->repoInfo().addBaseUrl(*i);
- }
- else
- repo->repoInfo().setBaseUrl(zypp::Url(u->value()));
- }
- catch (const zypp::Exception & excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error ("Cannot set the new URL for source %s (%lld): %s",
- repo->repoInfo().alias().c_str(), id->asInteger()->value(), excpt.msg().c_str());
- return YCPBoolean(false);
- }
-
- return YCPBoolean(true);
-}
-
-/****************************************************************************************
- * @builtin SourceInstallOrder
- *
- * @short not implemented, do not use (Explicitly set an install order.)
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceInstallOrder (const YCPMap& ord)
-{
- /* TODO FIXME
- YCPList args;
- args->add (ord);
-
- //-------------------------------------------------------------------------------------//
- YcpArgLoad decl(__FUNCTION__);
-
- YCPMap & order_map( decl.arg<YT_MAP, YCPMap>() );
-
- if ( ! decl.load( args ) ) {
- return pkgError_bad_args;
- }
- //-------------------------------------------------------------------------------------//
-
- InstSrcManager::InstOrder order;
- order.reserve( order_map->size() );
- bool error = false;
-
- for ( YCPMapIterator it = order_map->begin(); it != order_map->end(); ++it ) {
-
- if ( it.value()->isInteger() ) {
- InstSrc::UniqueID uId( it.value()->asInteger()->value() );
- InstSrcManager::ISrcId source_id( _y2pm.instSrcManager().getSourceByID( uId ) );
- if ( source_id ) {
- if ( source_id->enabled() ) {
- order.push_back( uId ); // finaly ;)
-
- } else {
- y2error ("order map entry '%s:%s': source not enabled",
- it.key()->toString().c_str(),
- it.value()->toString().c_str() );
- error = true;
- }
- } else {
- y2error ("order map entry '%s:%s': bad source id",
- it.key()->toString().c_str(),
- it.value()->toString().c_str() );
- error = true;
- }
- } else {
- y2error ("order map entry '%s:%s': integer value expected",
- it.key()->toString().c_str(),
- it.value()->toString().c_str() );
- error = true;
- }
- }
- if ( error ) {
- return pkgError( Error::E_bad_args );
- }
-
- // store new instorder
- _y2pm.instSrcManager().setInstOrder( order );
-*/
-
-#warning SourceInstallOrder is not implemented
- return YCPBoolean( true );
-}
-
-
-static std::string timestamp ()
-{
- time_t t = time(NULL);
- struct tm * tmp = localtime(&t);
-
- if (tmp == NULL) {
- return "";
- }
-
- char outstr[50];
- if (strftime(outstr, sizeof(outstr), "%Y%m%d-%H%M%S", tmp) == 0) {
- return "";
- }
- return outstr;
-}
-
-/**
- * Take the ?alias=foo part of old_url, if any, and return it,
- * putting the rest to new_url.
- * \throws Exception on malformed URLs I guess
- */
-static std::string removeAlias (const zypp::Url & old_url,
- zypp::Url & new_url)
-{
- std::string alias;
- new_url = old_url;
- zypp::url::ParamMap query = new_url.getQueryStringMap ();
- zypp::url::ParamMap::iterator alias_it = query.find ("alias");
- if (alias_it != query.end ())
- {
- alias = alias_it->second;
- query.erase (alias_it);
- new_url.setQueryStringMap (query);
- }
- return alias;
-}
-
-std::string PkgModuleFunctions::UniqueAlias(const std::string &alias)
-{
- // make a copy
- std::string ret = alias;
-
- unsigned int id = 0;
- while(aliasExists(ret))
- {
- y2milestone("Alias %s already found: %lld", ret.c_str(), logFindAlias(ret));
-
- // the alias already exists - add a counter
- std::ostringstream ostr;
- ostr << alias << "_" << id;
-
- ret = ostr.str();
-
- y2milestone("Using alias %s", ret.c_str());
- ++id;
- }
-
- return ret;
-}
-
-
-/**
- * helper - add "mountoptions=ro" for mountable URL schemes if "mountoptions" option is not empty and
- * "rw" or "ro" option is missing
- */
-zypp::Url addRO(const zypp::Url &url)
-{
- zypp::Url ret(url);
- std::string scheme = zypp::str::toLower(url.getScheme());
-
- if (scheme == "nfs"
- || scheme == "hd"
- || scheme == "smb"
- || scheme == "iso"
- || scheme == "cd"
- || scheme == "dvd"
- )
- {
- const std::string mountoptions = "mountoptions";
- zypp::media::Mount::Options options(url.getQueryParam(mountoptions));
-
- y2debug("Current mountoptions: %s", options.asString().c_str());
-
- // if mountoptions are empty lizypp uses "ro" by default
- // don't override "rw" option from application
- // don't add "ro" if it's already present
- if (!options.empty() && !options.has("rw") && !options.has("ro"))
- {
- options["ro"];
-
- ret.setQueryParam(mountoptions, options.asString());
- y2milestone("Adding read only mount option: '%s' -> '%s'", url.asString().c_str(), ret.asString().c_str());
- }
- }
-
- return ret;
-}
-
-// helper function
-zypp::Url PkgModuleFunctions::shortenUrl(const zypp::Url &url)
-{
- std::string url_path = url.getPathName();
- std::string begin_path;
- std::string end_path;
-
- // try to convert 'http://server/dir1/dir2/dir3/dir4' -> 'http://server/dir1/.../dir4'
- std::string::size_type pos_first = url_path.find("/");
- if (pos_first == 0)
- {
- pos_first = url_path.find("/", 1);
- }
-
- if (pos_first == std::string::npos)
- {
- const int num = 5;
-
- // "/" not found use the beginning and the end part
- // 'http://server/very_long_directory_name' -> 'http://server/very_..._name'
- begin_path = std::string(url_path, 0, num);
- end_path = std::string(url_path, url_path.size() - num - 1, num);
- }
- else
- {
- unsigned int pos_last = url_path.rfind("/");
- if (pos_last == url_path.size() - 1)
- {
- pos_last = url_path.rfind("/", url_path.size() - 1);
- }
-
- if (pos_last == pos_first || pos_last < pos_first)
- {
- const int num = 5;
-
- // "/" not found use the beginning and the end part
- begin_path = std::string(url_path, 0, num);
- end_path = std::string(url_path, url_path.size() - num - 1, num);
- }
- else
- {
- begin_path = std::string(url_path, 0, pos_first + 1);
- end_path = std::string(url_path, pos_last);
- }
- }
-
- std::string new_path = begin_path + "..." + end_path;
- zypp::Url ret(url);
-
- // use the shorter path
- ret.setPathName(new_path);
- // remove query parameters
- ret.setQueryString("");
- // remove fragmet
- ret.setFragment("");
-
- y2milestone("Using shortened URL: '%s' -> '%s'", url.asString().c_str(), ret.asString().c_str());
- return ret;
-}
-
-/** Create a Source and immediately put it into the SourceManager.
- * \return the SourceId
- * \throws Exception if Source creation fails
-*/
-std::vector<zypp::RepoInfo>::size_type
-PkgModuleFunctions::createManagedSource( const zypp::Url & url_r,
- const zypp::Pathname & path_r,
- const bool base_source,
- const std::string& type,
- const std::string &alias_r )
-{
- // parse URL
- y2milestone ("Original URL: %s, product directory: %s", url_r.asString().c_str(), path_r.asString().c_str());
-
- // #158850#c17, if the URL contains an alias, we use that
- zypp::Url url;
-
- std::string alias = removeAlias(url_r, url);
- y2milestone("Alias from URL: '%s'", alias.c_str());
-
-#warning FIXME: use base_source (base_source vs. addon) (will be probably not needed)
-
- // repository type
- zypp::repo::RepoType repotype;
- zypp::RepoManager repomanager = CreateRepoManager();
-
- if (!type.empty())
- {
- try
- {
- // do conversion from the Yast type ("YaST", "YUM", "Plaindir")
- // to libzypp type ("yast", "yum", "plaindir")
- repotype = repotype.parse(yast2zyppType(type));
- }
- catch (zypp::repo::RepoUnknownTypeException &e)
- {
- y2warning("Unknown source type '%s'", type.c_str());
- }
- }
-
- // the type is not specified or is wrong, autoprobe the type
- if (repotype == zypp::repo::RepoType::NONE)
- {
- zypp::Url probe_url(url_r);
-
- if (!path_r.asString().empty())
- {
- zypp::Pathname pth(probe_url.getPathName());
- pth /= path_r;
-
- probe_url.setPathName(pth.asString());
- }
-
- y2milestone("Probing source type: '%s'", probe_url.asString().c_str());
-
- // autoprobe type of the repository
- repotype = ProbeWithCallbacks(probe_url);
- }
-
- y2milestone("Using source type: %s", repotype.asString().c_str());
-
-
- // create source definition object
- zypp::RepoInfo repo;
-
- std::string name;
-
- // set alias and name
- if (alias.empty())
- {
- // alias not set via URL, use the passed alias or the URL path
- if (alias_r.empty())
- {
- // use the last path element in URL
- std::string url_path = url.getPathName();
-
- std::string::size_type pos_begin = url_path.rfind("/");
- std::string::size_type pos_end = std::string::npos;
-
- // ignore the trailing slash
- if (pos_begin == url_path.size() - 1)
- {
- pos_begin = url_path.rfind("/", url_path.size() - 2);
-
- if (pos_begin != std::string::npos)
- {
- pos_end = url_path.size() - pos_begin - 2;
- }
- }
- else
- {
- pos_end = url_path.size() - pos_begin - 1;
- }
-
- // ignore the found slash character
- pos_begin++;
-
- alias = std::string(url_path, pos_begin, pos_end);
-
- y2milestone("Alias from URL path: %s", alias.c_str());
-
- // fallback
- if (alias.empty())
- {
- y2milestone("URL alias is empty using 'Repository'");
- alias = "Repository";
- }
- }
- else
- {
- alias = alias_r;
- }
-
- name = alias;
- }
- else
- {
- name = alias;
- }
-
-
- y2milestone("Name of the repository: '%s'", name.c_str());
-
- // alias must be unique, add a suffix if it's already used
- alias = UniqueAlias(alias);
-
- // add read only mount option to the URL if needed
- url = addRO(url);
-
- bool autorefresh = true;
-
- std::string scheme = zypp::str::toLower(url.getScheme());
- if (scheme == "cd" || scheme == "dvd")
- {
- y2milestone("Disabling autorefresh for CD/DVD repository");
- autorefresh = false;
- }
-
- repo.setAlias(alias);
- repo.setName(name);
- repo.setType(repotype);
- repo.addBaseUrl(url);
- repo.setPath(path_r);
- repo.setEnabled(true);
- repo.setAutorefresh(autorefresh);
-
- // set metadata path (#293428)
- zypp::Pathname metadatapath = repomanager.metadataPath(repo);
- repo.setMetadataPath(metadatapath);
-
- y2milestone("Adding source '%s' (%s, dir: %s)", repo.alias().c_str(), url.asString().c_str(), path_r.asString().c_str());
- // note: exceptions should be caught by the calling code
- RefreshWithCallbacks(repo);
-
- // build cache if needed
- if (!repomanager.isCached(repo))
- {
- y2milestone("Caching source '%s'...", repo.alias().c_str());
- repomanager.buildCache(repo);
- }
-
- repos.push_back(new YRepo(repo));
-
- y2milestone("Added source '%s': '%s', enabled: %s, autorefresh: %s",
- repo.alias().c_str(),
- repo.baseUrlsBegin()->asString().c_str(),
- repo.enabled() ? "true" : "false",
- repo.autorefresh() ? "true" : "false"
- );
-
- // the source is at the end of the list
- return repos.size() - 1;
-}
-
-/****************************************************************************************
- * @builtin RepositoryAdd
- *
- * @short Register a new repository
- * @description
- * Adds a new repository to the internal structures. The repository is only registered,
- * metadata is not downloaded, use Pkg::SourceRefreshNow() for that. The metadata is also loaded
- * automatically when loading the repository content (Pkg::SourceLoad())
- *
- * @param map map with repository parameters: $[ "enabled" : boolean, "autorefresh" : boolean, "name" : string,
- * "alias" : string, "base_urls" : list<string>, "prod_dir" : string, "type" : string ]
- * @return integer Repository ID or nil on error
- **/
-YCPValue PkgModuleFunctions::RepositoryAdd(const YCPMap ¶ms)
-{
- zypp::RepoInfo repo;
-
- // turn on the repo by default
- repo.setEnabled(true);
- // enable autorefresh by default
- repo.setAutorefresh(true);
-
- if (!params->value( YCPString("enabled") ).isNull() && params->value(YCPString("enabled"))->isBoolean())
- {
- repo.setEnabled(params->value(YCPString("enabled"))->asBoolean()->value());
- }
-
- if (!params->value( YCPString("autorefresh") ).isNull() && params->value(YCPString("autorefresh"))->isBoolean())
- {
- repo.setAutorefresh(params->value(YCPString("autorefresh"))->asBoolean()->value());
- }
-
- std::string alias;
-
- if (!params->value( YCPString("alias") ).isNull() && params->value(YCPString("alias"))->isString())
- {
- alias = params->value(YCPString("alias"))->asString()->value();
- }
-
- if (alias.empty())
- {
- alias = timestamp();
-
- // the alias must be unique
- alias = UniqueAlias(alias);
- }
- else
- {
- if (aliasExists(alias))
- {
- ycperror("alias %s already exists", alias.c_str());
- return YCPVoid();
- }
- }
-
- repo.setAlias(alias);
-
- // use the first base URL as a fallback name
- std::string first_url;
-
- if (!params->value( YCPString("base_urls") ).isNull() && params->value(YCPString("base_urls"))->isList())
- {
- YCPList lst(params->value(YCPString("base_urls"))->asList());
-
- for (int index = 0; index < lst->size(); ++index)
- {
- if( ! lst->value(index)->isString() )
- {
- ycperror( "Pkg::RepositoryAdd(): entry not a string at index %d: %s", index, lst->toString().c_str());
- return YCPVoid();
- }
-
- zypp::Url url;
-
- try
- {
- url = lst->value(index)->asString()->value();
- zypp::Url url_new;
-
- std::string name = removeAlias(url, url_new);
-
- if (!name.empty())
- {
- repo.setName(name);
- url = url_new;
- }
-
- // add read only mount option to the URL if needed
- url = addRO(url);
- }
- catch(const zypp::Exception & expt)
- {
- y2error("Invalid URL: %s", expt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(expt));
- return YCPVoid();
- }
-
- if (index == 0)
- {
- first_url = url.asString();
- }
-
- repo.addBaseUrl(url);
- }
- }
- else
- {
- ycperror("Missing \"base_urls\" key in the map");
- return YCPVoid();
- }
-
- // check name parameter
- if (!params->value( YCPString("name") ).isNull() && params->value(YCPString("name"))->isString())
- {
- repo.setName(params->value(YCPString("name"))->asString()->value());
- }
- else
- {
- // if the key "name" is missing and the name hasn't been set by ?alias= in the URL
- // then use the first URL as the name
- if (repo.name().empty())
- {
- repo.setName(first_url);
- }
- }
-
- if (!params->value( YCPString("type") ).isNull() && params->value(YCPString("type"))->isString())
- {
- std::string type = yast2zyppType(params->value(YCPString("type"))->asString()->value());
-
- try
- {
- zypp::repo::RepoType repotype(type);
- repo.setType(repotype);
- }
- catch (zypp::repo::RepoUnknownTypeException &e)
- {
- ycperror("Unknown source type '%s': %s", type.c_str(), e.asString().c_str());
- _last_error.setLastError(ExceptionAsString(e));
- return YCPVoid();
- }
-
- }
-
- if (!params->value( YCPString("prod_dir") ).isNull() && params->value(YCPString("prod_dir"))->isString())
- {
- repo.setPath(params->value(YCPString("prod_dir"))->asString()->value());
- }
-
- // set metadata path (#293428)
- zypp::RepoManager repomanager = CreateRepoManager();
- zypp::Pathname metadatapath = repomanager.metadataPath(repo);
- repo.setMetadataPath(metadatapath);
-
- repos.push_back(new YRepo(repo));
-
- // the new source is at the end of the list
- return YCPInteger(repos.size() - 1);
-}
-
-/****************************************************************************************
- * @builtin SourceCacheCopyTo
- *
- * @short Copy cache data of all installation sources to the target
- * @description
- * Copy cache data of all installation sources to the target located below 'dir'.
- * To be called at end of initial installation.
- *
- * @param string dir Root directory of target.
- * @return boolean true on success
- **/
-YCPValue
-PkgModuleFunctions::SourceCacheCopyTo (const YCPString& dir)
-{
- // error message (followed by detailed description)
- const std::string msg = _("Error: Cannot copy the cache to the target directory\n");
-
- std::string d = dir->value();
- y2milestone("Copying source cache to '%s'...", d.c_str());
-
- if (d.empty())
- {
- y2error("Empty parameter in Pkg::SourceCacheCopyTo()!");
- return YCPBoolean(false);
- }
-
- std::string target = d + "/var/cache";
-
- // create the target dir
- const char* argv[] =
- {
- "mkdir",
- // create parent dir
- "-p",
- // finish parameter list
- "--",
- // target
- target.c_str(),
- NULL
- };
-
- // discard stderr, no pty, stderr_fd = -1, use the default locale
- zypp::ExternalProgram prog(argv, zypp::ExternalProgram::Discard_Stderr, false, -1, true);
-
- int code = prog.close();
-
- if (code)
- {
- // error message (followed by directory name)
- _last_error.setLastError(msg + _("Cannot create directory ") + target);
- y2error("Cannot create target directory %s", target.c_str());
- return YCPBoolean(false);
- }
-
- // copy /var/cache/zypp to the target system
- const char* argv2[] =
- {
- "cp",
- // preserve time stamps
- "-a",
- // recursive
- "-r",
- // finish parameter list
- "--",
- // source
- "/var/cache/zypp",
- // target
- target.c_str(),
- NULL
- };
-
- // discard stderr, no pty, stderr_fd = -1, use the default locale
- zypp::ExternalProgram prog2(argv2, zypp::ExternalProgram::Discard_Stderr, false, -1, true);
-
- int code2 = prog2.close();
-
- if (code2)
- {
- // error message
- _last_error.setLastError(msg + _("Copying failed"));
- y2error("Cannot copy /var/cache/zypp to %s", d.c_str());
- }
-
- return YCPBoolean(!code2);
-}
-
-/****************************************************************************************
- * @builtin SourceScan
- * @short Scan a Source Media
- * @description
- * Load all InstSrces found at media_url, i.e. all sources mentioned in /media.1/products.
- * If no /media.1/products is available, InstSrc is expected to be located directly
- * below media_url (product_dir: /).
- *
- * If a product_dir is provided, only the InstSrc located at media_url/product_dir is loaded.
- *
- * In contrary to @ref SourceCreate, InstSrces are loaded into the InstSrcManager,
- * but not enabled (packages and selections are not provided to the PackageManager),
- * and the SrcIds of <b>all</b> InstSrces found are returned.
- *
- * @param string url The media to scan.
- * @optarg string product_dir Restrict scan to a certain InstSrc located in media_url/product_dir.
- *
- * @return list<integer> list of SrcIds (integer).
- **/
-YCPValue
-PkgModuleFunctions::SourceScan (const YCPString& media, const YCPString& pd)
-{
- zypp::Url url;
-
- try {
- url = zypp::Url(media->value ());
- }
- catch(const zypp::Exception & expt )
- {
- y2error ("Invalid URL: %s", expt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(expt));
- return YCPList();
- }
-
- zypp::Pathname pn(pd->value ());
-
- YCPList ids;
- std::vector<zypp::RepoInfo>::size_type id;
-
- if ( pd->value().empty() ) {
-
- // scan all sources
- zypp::MediaProductSet products;
-
- try
- {
- y2milestone("Scanning products in %s ...", url.asString().c_str());
- ScanProductsWithCallBacks(url);
- products = available_products;
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("Scanning products for '%s' has failed"
- , url.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- return ids;
- }
-
- if( products.empty() )
- {
- // no products found, use the base URL instead
- zypp::MediaProductEntry entry;
- products.insert(entry);
- }
-
- for( zypp::MediaProductSet::const_iterator it = products.begin();
- it != products.end() ; ++it )
- {
- try
- {
- y2milestone("Using product %s in directory %s", it->_name.c_str(), it->_dir.c_str());
- id = createManagedSource(url, it->_dir, false, "", it->_name);
- ids->add( YCPInteger(id) );
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("SourceScan for '%s' product '%s' has failed"
- , url.asString().c_str(), pn.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- }
- }
- } else {
- y2debug("Creating source...");
-
- try
- {
- id = createManagedSource(url, pn, false, "", "");
- ids->add( YCPInteger(id) );
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("SourceScan for '%s' product '%s' has failed"
- , url.asString().c_str(), pn.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- }
- }
-
- y2milestone("Found sources: %s", ids->toString().c_str() );
-
- return ids;
-}
-
-/****************************************************************************************
- * @builtin SourceCreate
- *
- * @short Create a Source
- * @description
- * Load and enable all InstSrces found at media_url, i.e. all sources mentioned in /media.1/products.
- * If no /media.1/products is available, InstSrc is expected to be located directly below
- * media_url (product_dir: /).
- *
- * If a product_dir is provided, only the InstSrc located at media_url/product_dir is loaded
- * and enabled.
- *
- * @param string url The media to scan.
- * @optarg string product_dir Restrict scan to a certain InstSrc located in media_url/product_dir.
- *
- * @return integer The source_id of the first InstSrc found on the media.
- **/
-YCPValue
-PkgModuleFunctions::SourceCreate (const YCPString& media, const YCPString& pd)
-{
- // not base product, autoprobe source type
- return SourceCreateEx (media, pd, false, YCPString(""));
-}
-
-YCPValue
-PkgModuleFunctions::SourceCreateBase (const YCPString& media, const YCPString& pd)
-{
- // base product, autoprobe source type
- return SourceCreateEx (media, pd, true, YCPString(""));
-}
-
-/**
- * @builtin SourceCreateType
- * @short Create source of required type
- * @description
- * Create a source without autoprobing the source type. This builtin should be used only for "Plaindir" sources, because Plaindir sources are not automatically probed in SourceCreate() builtin.
- * @param media URL of the source
- * @param pd product directory (if empty the products will be searched)
- * @param type type of the source ("YaST", "YUM" or "Plaindir")
-*/
-
-YCPValue
-PkgModuleFunctions::SourceCreateType (const YCPString& media, const YCPString& pd, const YCPString& type)
-{
- // not base product, autoprobe source type
- return SourceCreateEx (media, pd, false, type);
-}
-
-YCPValue
-PkgModuleFunctions::SourceCreateEx (const YCPString& media, const YCPString& pd, bool base, const YCPString& source_type)
-{
- y2debug("Creating source...");
-
- zypp::Pathname pn(pd->value ());
-
- zypp::Url url;
-
- try {
- url = zypp::Url(media->value ());
- }
- catch(const zypp::Exception & expt )
- {
- y2error ("Invalid URL: %s", expt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(expt));
- return YCPInteger (-1LL);
- }
-
-
- YCPList ids;
- std::vector<zypp::RepoInfo>::size_type ret = -1;
-
- const std::string type = source_type->value();
-
- if ( pd->value().empty() ) {
- // scan all sources
- zypp::MediaProductSet products;
-
- try {
- ScanProductsWithCallBacks(url);
- products = available_products;
- }
- catch ( const zypp::Exception& excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error( "Cannot read the product list from the media" );
- return YCPInteger(-1LL);
- }
-
- if( products.empty() )
- {
- // no products found, use the base URL instead
- zypp::MediaProductEntry entry ;
- products.insert( entry );
- }
-
- for( zypp::MediaProductSet::const_iterator it = products.begin();
- it != products.end() ; ++it )
- {
- try
- {
- std::vector<zypp::RepoInfo>::size_type id = createManagedSource(url, it->_dir, base, type, it->_name);
- YRepo_Ptr repo = logFindRepository(id);
-
- LoadResolvablesFrom(repo->repoInfo());
-
- // return the id of the first product
- if ( it == products.begin() )
- ret = id;
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("SourceCreate for '%s' product '%s' has failed"
- , url.asString().c_str(), pn.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- return YCPInteger(-1LL);
- }
- }
- } else {
- y2debug("Creating source...");
-
- try
- {
- ret = createManagedSource(url, pn, base, type, "");
-
- YRepo_Ptr repo = logFindRepository(ret);
- repo->repoInfo().setEnabled(true);
-
- LoadResolvablesFrom(repo->repoInfo());
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("SourceCreate for '%s' product '%s' has failed"
- , url.asString().c_str(), pn.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- }
- }
-
- PkgFreshen();
- return YCPInteger(repos.size() - 1);
-}
-
-
-/****************************************************************************************
- * @builtin SourceSetEnabled
- *
- * @short Set the default activation state of an InsrSrc.
- * @param integer SrcId Specifies the InstSrc.
- * @param boolean enabled Default activation state of source.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceSetEnabled (const YCPInteger& id, const YCPBoolean& e)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- // no change required
- bool enable = e->value();
- if ((enable && repo->repoInfo().enabled())
- || (!enable && !repo->repoInfo().enabled()))
- return YCPBoolean(true);
-
- bool success = true;
-
- try
- {
- repo->repoInfo().setEnabled(enable);
-
- // add/remove resolvables
- if (enable)
- {
- // load resolvables only when they are missing
- if (!AnyResolvableFrom(repo->repoInfo().alias()))
- {
- success = LoadResolvablesFrom(repo->repoInfo());
- }
- }
- else
- {
- // the source has been disabled, remove resolvables from the pool
- RemoveResolvablesFrom(repo->repoInfo().alias());
- }
-
- PkgFreshen();
- }
- catch (const zypp::Exception& excpt)
- {
- std::string alias = repo->repoInfo().alias();
- y2error ("Error for '%s': %s", alias.c_str(), excpt.asString().c_str());
- _last_error.setLastError(alias + ": " + ExceptionAsString(excpt));
- success = false;
- }
-
- return YCPBoolean(success);
-}
-
-/****************************************************************************************
- * @builtin SourceSetAutorefresh
- *
- * @short Set whether this source should automaticaly refresh it's
- * meta data when it gets enabled. (default true, if not CD/DVD)
- * @param integer SrcId Specifies the InstSrc.
- * @param boolean enabled Whether autorefresh should be turned on or off.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceSetAutorefresh (const YCPInteger& id, const YCPBoolean& e)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- repo->repoInfo().setAutorefresh(e->value());
-
- return YCPBoolean( true );
-}
-
-/****************************************************************************************
- * @builtin SourceFinish
- * @short Disable an Installation Source
- * @param integer SrcId Specifies the InstSrc.
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceFinish (const YCPInteger& id)
-{
- return SourceSetEnabled(id, false);
-}
-
-/****************************************************************************************
- * @builtin SourceRefreshNow
- * @short Attempt to immediately refresh a Source
- * @description
- * The InsrSrc will be encouraged to check and refresh all metadata
- * cached on disk.
- *
- * @param integer SrcId Specifies the InstSrc.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceRefreshNow (const YCPInteger& id)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- try
- {
- zypp::RepoManager repomanager = CreateRepoManager();
- y2milestone("Refreshing metadata '%s'", repo->repoInfo().alias().c_str());
- RefreshWithCallbacks(repo->repoInfo());
-
- y2milestone("Caching source '%s'...", repo->repoInfo().alias().c_str());
- repomanager.buildCache(repo->repoInfo());
- }
- catch ( const zypp::Exception & expt )
- {
- y2error ("Error while refreshing the source: %s", expt.asString().c_str());
- _last_error.setLastError(repo->repoInfo().alias() + ": " + ExceptionAsString(expt));
- return YCPBoolean(false);
- }
-
- return YCPBoolean( true );
-}
-
-/****************************************************************************************
- * @builtin SourceDelete
- * @short Delete a Source
- * @description
- * Delete an InsrSrc. The InsrSrc together with all metadata cached on disk
- * is removed. The SrcId passed becomes invalid (other SrcIds stay valid).
- *
- * @param integer SrcId Specifies the InstSrc.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceDelete (const YCPInteger& id)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- bool success = true;
-
- try
- {
- // the resolvables cannot be used anymore, remove them
- RemoveResolvablesFrom(repo->repoInfo().alias());
-
- // update 'repos'
- repo->setDeleted();
-
- PkgFreshen();
- }
- catch (const zypp::Exception& excpt)
- {
- std::string alias = repo->repoInfo().alias();
- y2error ("Error for '%s': %s", alias.c_str(), excpt.asString().c_str());
- _last_error.setLastError(alias + ": " + ExceptionAsString(excpt));
- success = false;
- }
-
- return YCPBoolean(success);
-}
-
-/****************************************************************************************
- * @builtin SourceEditGet
- *
- * @short Get state of Sources
- * @description
- * Return a list of states for all known InstSources sorted according to the
- * source priority (highest first). A source state is a map:
- * $[
- * "SrcId" : YCPInteger,
- * "enabled" : YCPBoolean
- * "autorefresh": YCPBoolean
- * ];
- *
- * @return list<map> list of source states (map)
- **/
-YCPValue
-PkgModuleFunctions::SourceEditGet ()
-{
- YCPList ret;
-
- unsigned long index = 0;
- for( std::vector<YRepo_Ptr>::const_iterator it = repos.begin(); it != repos.end(); ++it, ++index)
- {
- if (!(*it)->isDeleted())
- {
- YCPMap src_map;
-
- src_map->add(YCPString("SrcId"), YCPInteger(index));
- // Note: enabled() is tribool
- src_map->add(YCPString("enabled"), YCPBoolean((*it)->repoInfo().enabled()));
- // Note: autorefresh() is tribool
- src_map->add(YCPString("autorefresh"), YCPBoolean((*it)->repoInfo().autorefresh()));
- src_map->add(YCPString("name"), YCPString((*it)->repoInfo().name()));
-
- ret->add(src_map);
- }
- }
-
- return ret;
-}
-
-/****************************************************************************************
- * @builtin SourceEditSet
- *
- * @short Configure properties of installation sources
- * @description
- * Set states of installation sources. Note: Enabling/disabling a source does not
- * (un)load the packages from the source! Use SourceSetEnabled() if you need to refresh
- * the packages in the pool.
- *
- * @param list source_states List of source states. Same format as returned by
- * @see SourceEditGet.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceEditSet (const YCPList& states)
-{
- bool error = false;
-
- for (int index = 0; index < states->size(); index++ )
- {
- if( ! states->value(index)->isMap() )
- {
- ycperror( "Pkg::SourceEditSet, entry not a map at index %d", index);
- error = true;
- continue;
- }
-
- YCPMap descr = states->value(index)->asMap();
-
- if (descr->value( YCPString("SrcId") ).isNull() || !descr->value(YCPString("SrcId"))->isInteger())
- {
- ycperror( "Pkg::SourceEditSet, SrcId not defined for a source description at index %d", index);
- error = true;
- continue;
- }
-
- std::vector<YRepo_Ptr>::size_type id = descr->value( YCPString("SrcId") )->asInteger()->value();
-
- YRepo_Ptr repo = logFindRepository(id);
- if (!repo)
- {
- ycperror( "Pkg::SourceEditSet, source %d not found", index);
- error = true;
- continue;
- }
-
- // now, we have the source
- if( ! descr->value( YCPString("enabled")).isNull() && descr->value(YCPString("enabled"))->isBoolean ())
- {
- bool enable = descr->value(YCPString("enabled"))->asBoolean ()->value();
-
- if (repo->repoInfo().enabled() != enable)
- {
- ycpwarning("Pkg::SourceEditSet() does not refresh the pool (src: %zd, state: %s)", id, enable ? "disabled -> enabled" : "enabled -> disabled");
- }
-
- y2debug("set enabled: %d", enable);
- repo->repoInfo().setEnabled(enable);
- }
-
- if( !descr->value(YCPString("autorefresh")).isNull() && descr->value(YCPString("autorefresh"))->isBoolean ())
- {
- bool autorefresh = descr->value(YCPString("autorefresh"))->asBoolean()->value();
- y2debug("set autorefresh: %d", autorefresh);
- repo->repoInfo().setAutorefresh( autorefresh );
- }
-
- if( !descr->value(YCPString("name")).isNull() && descr->value(YCPString("name"))->isString())
- {
- // rename the source
- y2debug("set name: %s", descr->value(YCPString("name"))->asString()->value().c_str());
- repo->repoInfo().setName(descr->value(YCPString("name"))->asString()->value());
- }
-
-#warning SourceEditSet ordering not implemented yet
- }
-
- PkgFreshen();
- return YCPBoolean( !error );
-}
-
-/////////////////////////////////////////////////////////////////////////////////////////
-//
-// DEPRECATED
-//
-/////////////////////////////////////////////////////////////////////////////////////////
-
-/****************************************************************************************
- * Pkg::SourceRaisePriority (integer SrcId) -> bool
- *
- * Raise priority of source.
- *
- * @param SrcId Specifies the InstSrc.
- *
- * @return bool
- **/
-YCPValue
-PkgModuleFunctions::SourceRaisePriority (const YCPInteger& id)
-{
-#warning SourceRaisePriority is not implemented
- y2warning("SourceRaisePriority is NOT implemented");
-/* zypp::Source_Ref src;
-
- try {
- src = logFindRepository(id->value());
- }
- catch (const zypp::Exception& excpt)
- {
- return YCPBoolean(false);
- }
-
- // raise priority by one
- src.setPriority(src.priority() + 1);
-*/
-
- return YCPBoolean( true );
-
-}
-
-/****************************************************************************************
- * Pkg::SourceLowerPriority (integer SrcId) -> void
- *
- * Lower priority of source.
- *
- * @param SrcId Specifies the InstSrc.
+ * @param string url The media to scan.
+ * @optarg string product_dir Restrict scan to a certain InstSrc located in media_url/product_dir.
*
- * @return bool
- */
+ * @return integer The source_id of the first InstSrc found on the media.
+ **/
YCPValue
-PkgModuleFunctions::SourceLowerPriority (const YCPInteger& id)
+PkgModuleFunctions::SourceCreate (const YCPString& media, const YCPString& pd)
{
-#warning SourceLowerPriority is not implemented
- y2warning("SourceLowerPriority is NOT implemented");
-/*
- zypp::Source_Ref src;
+ // not base product, autoprobe source type
+ return SourceCreateEx (media, pd, false, YCPString(""));
+}
- try {
- src = logFindRepository(id->value());
- }
- catch (const zypp::Exception& excpt)
- {
- return YCPBoolean(false);
- }
+YCPValue
+PkgModuleFunctions::SourceCreateBase (const YCPString& media, const YCPString& pd)
+{
+ // base product, autoprobe source type
+ return SourceCreateEx (media, pd, true, YCPString(""));
+}
- // lower priority by one
- src.setPriority(src.priority() - 1);
+/**
+ * @builtin SourceCreateType
+ * @short Create source of required type
+ * @description
+ * Create a source without autoprobing the source type. This builtin should be used only for "Plaindir" sources, because Plaindir sources are not automatically probed in SourceCreate() builtin.
+ * @param media URL of the source
+ * @param pd product directory (if empty the products will be searched)
+ * @param type type of the source ("YaST", "YUM" or "Plaindir")
*/
- return YCPBoolean( true );
-}
-/****************************************************************************************
- * Pkg::SourceSaveRanks () -> boolean
- *
- * @short Obsoleted function, do not use
- * @return boolean true
- **/
YCPValue
-PkgModuleFunctions::SourceSaveRanks ()
+PkgModuleFunctions::SourceCreateType (const YCPString& media, const YCPString& pd, const YCPString& type)
{
- y2error( "SourceSaveRanks not implemented" );
-
- return YCPBoolean( true );
+ // not base product, autoprobe source type
+ return SourceCreateEx (media, pd, false, type);
}
-/****************************************************************************************
- * @builtin SourceMoveDownloadArea
- *
- * @short Move download area of CURL-based sources to specified directory
- * @param path specifies the path to move the download area to
- * @return boolean
- **/
YCPValue
-PkgModuleFunctions::SourceMoveDownloadArea (const YCPString & path)
+PkgModuleFunctions::SourceCreateEx (const YCPString& media, const YCPString& pd, bool base, const YCPString& source_type)
{
- try
- {
- y2milestone("Moving download area of all sources to %s", path->value().c_str());
- zypp::media::MediaManager manager;
- manager.setAttachPrefix(path->value());
+ y2debug("Creating source...");
+
+ zypp::Pathname pn(pd->value ());
+
+ zypp::Url url;
+
+ try {
+ url = zypp::Url(media->value ());
+ }
+ catch(const zypp::Exception & expt )
+ {
+ y2error ("Invalid URL: %s", expt.asString().c_str());
+ _last_error.setLastError(ExceptionAsString(expt));
+ return YCPInteger (-1LL);
+ }
+
+
+ YCPList ids;
+ std::vector<zypp::RepoInfo>::size_type ret = -1;
+
+ const std::string type = source_type->value();
+
+ if ( pd->value().empty() ) {
+ // scan all sources
+ zypp::MediaProductSet products;
+
+ try {
+ ScanProductsWithCallBacks(url);
+ products = available_products;
}
- catch (zypp::Exception & excpt)
+ catch ( const zypp::Exception& excpt)
{
_last_error.setLastError(ExceptionAsString(excpt));
- y2error("Pkg::SourceMoveDownloadArea has failed: %s", excpt.msg().c_str());
- return YCPBoolean(false);
+ y2error( "Cannot read the product list from the media" );
+ return YCPInteger(-1LL);
}
- y2milestone( "Download areas moved");
-
- return YCPBoolean(true);
-}
-
-/*
- * A helper function - remove all resolvables from the repository from the pool
- */
-void PkgModuleFunctions::RemoveResolvablesFrom(const std::string &alias)
-{
- // remove the resolvables if they have been loaded
- // FIXME: can be implemented better? we need a ResStore object for removing,
- // which means search for a resolvable in the pool and get the Repository
- // object which can be asked for all resolvables in it
- for (zypp::ResPool::const_iterator it = zypp_ptr()->pool().begin()
- ; it != zypp_ptr()->pool().end()
- ; ++it)
+ if( products.empty() )
{
- if (it->resolvable()->repository().info().alias() == alias)
- {
- y2milestone("Removing all resolvables from '%s' from the pool...", alias.c_str());
- zypp_ptr()->removeResolvables(it->resolvable()->repository().resolvables());
- break;
- }
+ // no products found, use the base URL instead
+ zypp::MediaProductEntry entry ;
+ products.insert( entry );
}
-}
-/*
- * A helper function - is there any resolvable from the repository in the pool?
- */
-bool PkgModuleFunctions::AnyResolvableFrom(const std::string &alias)
-{
- for (zypp::ResPool::const_iterator it = zypp_ptr()->pool().begin()
- ; it != zypp_ptr()->pool().end()
- ; ++it)
+ for( zypp::MediaProductSet::const_iterator it = products.begin();
+ it != products.end() ; ++it )
{
- if (it->resolvable()->repository().info().alias() == alias)
+ try
{
- return true;
- }
- }
-
- return false;
-}
-
-/*
- * A helper function - load resolvable from the repository into the pool
- * Warning: Use AnyResolvableFrom() method for checing if the resolvables might be already loaded
- */
-bool PkgModuleFunctions::LoadResolvablesFrom(const zypp::RepoInfo &repoinfo)
-{
- bool success = true;
- unsigned int size_start = zypp_ptr()->pool().size();
- y2milestone("Loading resolvables from '%s', pool size at start: %d", repoinfo.alias().c_str(), size_start);
+ std::vector<zypp::RepoInfo>::size_type id = createManagedSource(url, it->_dir, base, type, it->_name);
+ YRepo_Ptr repo = logFindRepository(id);
- try
- {
- zypp::RepoManager repomanager = CreateRepoManager();
+ LoadResolvablesFrom(repo->repoInfo());
- // build cache if needed
- if (!repomanager.isCached(repoinfo))
+ // return the id of the first product
+ if ( it == products.begin() )
+ ret = id;
+ }
+ catch ( const zypp::Exception& excpt)
{
- zypp::RepoStatus raw_metadata_status = repomanager.metadataStatus(repoinfo);
- if (raw_metadata_status.empty())
- {
- y2milestone("Missing metadata for source '%s', downloading...", repoinfo.alias().c_str());
- RefreshWithCallbacks(repoinfo);
- }
-
- y2milestone("Caching source '%s'...", repoinfo.alias().c_str());
- repomanager.buildCache(repoinfo);
+ y2error("SourceCreate for '%s' product '%s' has failed"
+ , url.asString().c_str(), pn.asString().c_str());
+ _last_error.setLastError(ExceptionAsString(excpt));
+ return YCPInteger(-1LL);
}
+ }
+ } else {
+ y2debug("Creating source...");
- zypp::Repository repository = repomanager.createFromCache(repoinfo);
- const zypp::ResStore &store = repository.resolvables();
+ try
+ {
+ ret = createManagedSource(url, pn, base, type, "");
- // load resolvables
- zypp_ptr()->addResolvables(store);
+ YRepo_Ptr repo = logFindRepository(ret);
+ repo->repoInfo().setEnabled(true);
- y2milestone("Loaded %zd resolvables", store.size());
- }
- catch(const zypp::repo::RepoNotCachedException &excpt )
- {
- std::string alias = repoinfo.alias();
- y2error ("Resolvables from '%s' havn't been loaded: %s", alias.c_str(), excpt.asString().c_str());
- _last_error.setLastError("'" + alias + "': " + ExceptionAsString(excpt));
- success = false;
-
- // FIXME ??
- /*
- // disable the source
- y2error("Disabling source %s", url.c_str());
- repo->disable();
- */
+ LoadResolvablesFrom(repo->repoInfo());
}
- catch (const zypp::Exception& excpt)
+ catch ( const zypp::Exception& excpt)
{
- std::string alias = repoinfo.alias();
- y2internal("Error: Loading resolvables failed: %s", ExceptionAsString(excpt).c_str());
- _last_error.setLastError("'" + alias + "': " + ExceptionAsString(excpt));
- success = false;
+ y2error("SourceCreate for '%s' product '%s' has failed"
+ , url.asString().c_str(), pn.asString().c_str());
+ _last_error.setLastError(ExceptionAsString(excpt));
}
+ }
- unsigned int size_end = zypp_ptr()->pool().size();
- y2milestone("Pool size at end: %d (loaded %d resolvables)", size_end, size_end - size_start);
- return success;
+ PkgFreshen();
+ return YCPInteger(repos.size() - 1);
}
/****************************************************************************************
@@ -2853,6 +681,109 @@
return YCPString(ret);
}
+
+/****************************************************************************************
+ * @builtin SourceScan
+ * @short Scan a Source Media
+ * @description
+ * Load all InstSrces found at media_url, i.e. all sources mentioned in /media.1/products.
+ * If no /media.1/products is available, InstSrc is expected to be located directly
+ * below media_url (product_dir: /).
+ *
+ * If a product_dir is provided, only the InstSrc located at media_url/product_dir is loaded.
+ *
+ * In contrary to @ref SourceCreate, InstSrces are loaded into the InstSrcManager,
+ * but not enabled (packages and selections are not provided to the PackageManager),
+ * and the SrcIds of <b>all</b> InstSrces found are returned.
+ *
+ * @param string url The media to scan.
+ * @optarg string product_dir Restrict scan to a certain InstSrc located in media_url/product_dir.
+ *
+ * @return list<integer> list of SrcIds (integer).
+ **/
+YCPValue
+PkgModuleFunctions::SourceScan (const YCPString& media, const YCPString& pd)
+{
+ zypp::Url url;
+
+ try {
+ url = zypp::Url(media->value ());
+ }
+ catch(const zypp::Exception & expt )
+ {
+ y2error ("Invalid URL: %s", expt.asString().c_str());
+ _last_error.setLastError(ExceptionAsString(expt));
+ return YCPList();
+ }
+
+ zypp::Pathname pn(pd->value ());
+
+ YCPList ids;
+ std::vector<zypp::RepoInfo>::size_type id;
+
+ if ( pd->value().empty() ) {
+
+ // scan all sources
+ zypp::MediaProductSet products;
+
+ try
+ {
+ y2milestone("Scanning products in %s ...", url.asString().c_str());
+ ScanProductsWithCallBacks(url);
+ products = available_products;
+ }
+ catch ( const zypp::Exception& excpt)
+ {
+ y2error("Scanning products for '%s' has failed"
+ , url.asString().c_str());
+ _last_error.setLastError(ExceptionAsString(excpt));
+ return ids;
+ }
+
+ if( products.empty() )
+ {
+ // no products found, use the base URL instead
+ zypp::MediaProductEntry entry;
+ products.insert(entry);
+ }
+
+ for( zypp::MediaProductSet::const_iterator it = products.begin();
+ it != products.end() ; ++it )
+ {
+ try
+ {
+ y2milestone("Using product %s in directory %s", it->_name.c_str(), it->_dir.c_str());
+ id = createManagedSource(url, it->_dir, false, "", it->_name);
+ ids->add( YCPInteger(id) );
+ }
+ catch ( const zypp::Exception& excpt)
+ {
+ y2error("SourceScan for '%s' product '%s' has failed"
+ , url.asString().c_str(), pn.asString().c_str());
+ _last_error.setLastError(ExceptionAsString(excpt));
+ }
+ }
+ } else {
+ y2debug("Creating source...");
+
+ try
+ {
+ id = createManagedSource(url, pn, false, "", "");
+ ids->add( YCPInteger(id) );
+ }
+ catch ( const zypp::Exception& excpt)
+ {
+ y2error("SourceScan for '%s' product '%s' has failed"
+ , url.asString().c_str(), pn.asString().c_str());
+ _last_error.setLastError(ExceptionAsString(excpt));
+ }
+ }
+
+ y2milestone("Found sources: %s", ids->toString().c_str() );
+
+ return ids;
+}
+
/****************************************************************************************
* @builtin RepositoryScan
*
@@ -2900,41 +831,3 @@
return ret;
}
-// convert libzypp type to yast strings ("YaST", "YUM" or "Plaindir")
-std::string PkgModuleFunctions::zypp2yastType(const std::string &type)
-{
- std::string ret(type);
-
- if (type_conversion_table.empty())
- {
- // initialize the conversion map
- type_conversion_table["rpm-md"] = "YUM";
- type_conversion_table["yast2"] = "YaST";
- type_conversion_table["plaindir"] = "Plaindir";
- type_conversion_table["NONE"] = "NONE";
- }
-
- std::map<std::string,std::string>::const_iterator it = type_conversion_table.find(type);
-
- // found in the conversion table
- if (it != type_conversion_table.end())
- {
- ret = it->second;
- }
- else
- {
- y2error("Cannot convert type '%s'", type.c_str());
- }
-
- return ret;
-}
-
-std::string PkgModuleFunctions::yast2zyppType(const std::string &type)
-{
- // do conversion from the Yast type ("YaST", "YUM", "Plaindir")
- // to libzypp type ("yast", "yum", "plaindir")
- // we can simply use toLower instead of a conversion table
- // in this case
- return zypp::str::toLower(type);
-}
-
Copied: trunk/pkg-bindings/src/Source_Download.cc (from r42708, trunk/pkg-bindings/src/Source.cc)
URL: http://svn.opensuse.org/viewcvs/yast/trunk/pkg-bindings/src/Source_Download…
==============================================================================
--- trunk/pkg-bindings/src/Source.cc (original)
+++ trunk/pkg-bindings/src/Source_Download.cc Thu Dec 6 07:56:58 2007
@@ -1,2940 +1,250 @@
-/*---------------------------------------------------------------------\
-| |
-| __ __ ____ _____ ____ |
-| \ \ / /_ _/ ___|_ _|___ \ |
-| \ V / _` \___ \ | | __) | |
-| | | (_| |___) || | / __/ |
-| |_|\__,_|____/ |_| |_____| |
-| |
-| core system |
-| (C) SuSE GmbH |
-\----------------------------------------------------------------------/
-
- File: PkgModuleFunctionsSource.cc
-
- Author: Klaus Kaempf <kkaempf(a)suse.de>
- Maintainer: Klaus Kaempf <kkaempf(a)suse.de>
-
- Summary: Access to Installation Sources
- Namespace: Pkg
- Purpose: Access to InstSrc
- Handles source related Pkg::function (list_of_arguments) calls
- from WFMInterpreter.
-/-*/
-//#include <unistd.h>
-//#include <sys/statvfs.h>
-
-#include <iostream>
+/* ------------------------------------------------------------------------------
+ * Copyright (c) 2007 Novell, Inc. All Rights Reserved.
+ *
+ *
+ * This program is free software; you can redistribute it and/or modify it under
+ * the terms of version 2 of the GNU General Public License as published by the
+ * Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+ * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along with
+ * this program; if not, contact Novell, Inc.
+ *
+ * To contact Novell about this file by physical or electronic mail, you may find
+ * current contact information at www.novell.com.
+ * ------------------------------------------------------------------------------
+ */
-#include <ycpTools.h>
-#include <PkgModule.h>
-#include <PkgModuleFunctions.h>
+/*
+ File: $Id:$
+ Author: Ladislav Slezák <lslezak(a)novell.com>
+ Summary: Functions for downloading files from a repository
+*/
#include <Callbacks.h>
#include <Callbacks.YCP.h>
-#include <zypp/Product.h>
-#include <zypp/media/MediaManager.h>
-#include <zypp/media/Mount.h>
-#include <zypp/Pathname.h>
-
-#include <zypp/RepoInfo.h>
-#include <zypp/RepoManager.h>
-#include <zypp/Fetcher.h>
-#include <zypp/repo/RepoType.h>
-#include <zypp/MediaProducts.h>
-#include <zypp/ExternalProgram.h>
-#include <zypp/ProgressData.h>
-
-#include <sstream> // ostringstream
-
-#include <PkgProgress.h>
+#include <PkgModule.h>
+#include <PkgModuleFunctions.h>
-/*
- Textdomain "pkg-bindings"
-*/
-// scanned available products
-// hack: zypp/MediaProducts.h cannot be included in PkgModuleFunctions.h
-zypp::MediaProductSet available_products;
-
-// this method should be used instead of zypp::productsInMedia()
-// it initializes the download callbacks
-void PkgModuleFunctions::ScanProductsWithCallBacks(const zypp::Url &url)
+YCPValue PkgModuleFunctions::SourceProvideFileCommon(const YCPInteger &id,
+ const YCPInteger &mid,
+ const YCPString& f,
+ const YCPBoolean & optional)
{
- CallInitDownload(std::string(_("Scanning products in ") + url.asString()));
+ CallInitDownload(std::string(_("Downloading ") + f->value()));
+
+ bool found = true;
+ YRepo_Ptr repo = logFindRepository(id->value());
+ if (!repo)
+ found = false;
extern ZyppRecipients::MediaChangeSensitivity _silent_probing;
// remember the current value
ZyppRecipients::MediaChangeSensitivity _silent_probing_old = _silent_probing;
// disable media change callback for optional file
- _silent_probing = ZyppRecipients::MEDIA_CHANGE_DISABLE;
-
- y2milestone("Scanning products in %s ...", url.asString().c_str());
+ if (optional->value())
+ _silent_probing = ZyppRecipients::MEDIA_CHANGE_OPTIONALFILE;
- try
- {
- available_products.clear();
- zypp::productsInMedia(url, available_products);
- }
- catch(...)
+ zypp::filesystem::Pathname path; // FIXME use ManagedMedia
+ if (found)
{
- // call the final event even in case of exception
- CallDestDownload();
-
- // restore the probing flag
- _silent_probing = _silent_probing_old;
+ try
+ {
+ path = repo->mediaAccess()->provideFile(f->value(), mid->value());
+ y2milestone("local path: '%s'", path.asString().c_str());
+ }
+ catch (const zypp::Exception& excpt)
+ {
+ found = false;
- // rethrow the execption
- throw;
+ if (!optional->value())
+ {
+ _last_error.setLastError(ExceptionAsString(excpt));
+ y2milestone("File not found: %s", f->value_cstr());
+ }
+ }
}
- CallDestDownload();
-
- // restore the probing flag
+ // set the original probing value
_silent_probing = _silent_probing_old;
-}
-void PkgModuleFunctions::CallSourceReportStart(const std::string &text)
-{
- // get the YCP callback handler
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_SourceReportStart);
+ CallDestDownload();
- // is the callback registered?
- if (ycp_handler != NULL)
+ if (found)
{
- // add parameters
- ycp_handler->appendParameter( YCPInteger(0LL) );
- ycp_handler->appendParameter( YCPString("") );
- ycp_handler->appendParameter( YCPString(text) );
- // evaluate the callback function
- ycp_handler->evaluateCall();
+ return YCPString(path.asString());
}
-}
-
-void PkgModuleFunctions::CallSourceReportEnd(const std::string &text)
-{
- // get the YCP callback handler for end event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_SourceReportEnd);
-
- // is the callback registered?
- if (ycp_handler != NULL)
+ else
{
- // add parameters
- ycp_handler->appendParameter( YCPInteger(0LL) );
- ycp_handler->appendParameter( YCPString("") );
- ycp_handler->appendParameter( YCPString(text) );
- ycp_handler->appendParameter( YCPString("NO_ERROR") );
- ycp_handler->appendParameter( YCPString("") );
- // evaluate the callback function
- ycp_handler->evaluateCall();
+ return YCPVoid();
}
}
-void PkgModuleFunctions::CallSourceReportInit()
-{
- // get the YCP callback handler for init event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_SourceReportInit);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-void PkgModuleFunctions::CallSourceReportDestroy()
+/****************************************************************************************
+ * @builtin SourceProvideFile
+ *
+ * @short Make a file available at the local filesystem
+ * @description
+ * Let an InstSrc provide some file (make it available at the local filesystem).
+ *
+ * @param integer SrcId Specifies the InstSrc .
+ * @param integer medianr Number of the media the file is located on ('1' for the 1st media).
+ * @param string file Filename relative to the media root.
+ *
+ * @return string local path as string
+ **/
+YCPValue
+PkgModuleFunctions::SourceProvideFile (const YCPInteger& id, const YCPInteger& mid, const YCPString& f)
{
- // get the YCP callback handler for destroy event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_SourceReportDestroy);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
+ return SourceProvideFileCommon(id, mid, f, false /*optional*/);
}
-void PkgModuleFunctions::CallInitDownload(const std::string &task)
+/****************************************************************************************
+ * @builtin SourceProvideOptionalFile
+ *
+ * @short Make an optional file available at the local filesystem
+ * @description
+ * Let an InstSrc provide some file (make it available at the local filesystem).
+ * If the file doesn't exist don't ask user for another medium and return nil
+ *
+ * @param integer SrcId Specifies the InstSrc .
+ * @param integer medianr Number of the media the file is located on ('1' for the 1st media).
+ * @param string file Filename relative to the media root.
+ *
+ * @return string local path as string
+ **/
+YCPValue
+PkgModuleFunctions::SourceProvideOptionalFile (const YCPInteger& id, const YCPInteger& mid, const YCPString& f)
{
- // get the YCP callback handler for destroy event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_InitDownload);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- ycp_handler->appendParameter(YCPString(task));
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
+ return SourceProvideFileCommon(id, mid, f, true /*optional*/);
}
-void PkgModuleFunctions::CallDestDownload()
+/****************************************************************************************
+ * @builtin SourceProvideDir
+ * @short make a directory available at the local filesystem
+ * @description
+ * Let an InstSrc provide some directory (make it available at the local filesystem) and
+ * all the files within it (non recursive).
+ *
+ * @param integer SrcId Specifies the InstSrc .
+ * @param integer medianr Number of the media the file is located on ('1' for the 1st media).
+ * @param string dir Directoryname relative to the media root.
+ * @return string local path as string
+ */
+YCPValue
+PkgModuleFunctions::SourceProvideDir (const YCPInteger& id, const YCPInteger& mid, const YCPString& d)
{
- // get the YCP callback handler for destroy event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_DestDownload);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
+ y2warning("Pkg::SourceProvideDir() is obsoleted use Pkg::SourceProvideDirectory() instead");
+ // non optional, non recursive
+ return SourceProvideDirectory(id, mid, d, false, false);
}
-// this method should be used instead of RepoManager::refreshMetadata()
-void PkgModuleFunctions::RefreshWithCallbacks(const zypp::RepoInfo &repo)
-{
- CallInitDownload(std::string(_("Refreshing repository ") + repo.alias()));
-
- try
- {
- zypp::RepoManager repomanager = CreateRepoManager();
- repomanager.refreshMetadata(repo);
- }
- catch(...)
- {
- // call the final event even in case of exception
- CallDestDownload();
- // rethrow the execption
- throw;
- }
- CallDestDownload();
-}
-
-// this method should be used instead of RepoManager::probe()
-zypp::repo::RepoType PkgModuleFunctions::ProbeWithCallbacks(const zypp::Url &url)
+/****************************************************************************************
+ * @builtin SourceProvideDirectory
+ * @short make a directory available at the local filesystem
+ * @description
+ * Download a directory from repository (make it available at the local filesystem) and
+ * all the files within it.
+ *
+ * @param integer id repository to use (id)
+ * @param integer mid Number of the media where the directory is located on ('1' for the 1st media).
+ * @param string d Directory name relative to the media root.
+ * @param boolean optional set to true if the directory may not exist (do not report errors)
+ * @param boolean recursive set to true to provide all subdirectories recursively
+ * @return string local path as string or nil when an error occured
+ */
+YCPValue
+PkgModuleFunctions::SourceProvideDirectory(const YCPInteger& id, const YCPInteger& mid, const YCPString& d, const YCPBoolean &optional, const YCPBoolean &recursive)
{
- CallInitDownload(std::string(_("Probing repository ") + url.asString()));
+ CallInitDownload(std::string(_("Downloading ") + d->value()));
+
+ bool found = true;
+ YRepo_Ptr repo = logFindRepository(id->value());
+ if (!repo)
+ found = false;
- zypp::repo::RepoType repotype;
+ zypp::filesystem::Pathname path; // FIXME user ManagedMedia
extern ZyppRecipients::MediaChangeSensitivity _silent_probing;
// remember the current value
ZyppRecipients::MediaChangeSensitivity _silent_probing_old = _silent_probing;
// disable media change callback for optional file
- _silent_probing = ZyppRecipients::MEDIA_CHANGE_DISABLE;
-
- try
- {
- // probe type of the repository
- zypp::RepoManager repomanager = CreateRepoManager();
- repotype = repomanager.probe(url);
- }
- catch(...)
- {
- // call the final event even in case of exception
- CallDestDownload();
-
- // restore the probing flag
- _silent_probing = _silent_probing_old;
-
- // rethrow the execption
- throw;
- }
-
- CallDestDownload();
-
- // restore the probing flag
- _silent_probing = _silent_probing_old;
-
- return repotype;
-}
+ if (optional->value())
+ _silent_probing = ZyppRecipients::MEDIA_CHANGE_OPTIONALFILE;
-/**
- * Logging helper:
- * call zypp::SourceManager::sourceManager()->findSource
- * and in case of exception, log error and setLastError AND RETHROW
- */
-YRepo_Ptr PkgModuleFunctions::logFindRepository(std::vector<YRepo_Ptr>::size_type id)
-{
- try
+ if (found)
{
- if (id < 0 || id >= repos.size())
- {
- // not found
- throw(std::exception());
- }
-
- if (!repos[id])
+ try
{
- // not found
- throw(std::exception());
+ path = repo->mediaAccess()->provideDir(d->value(), recursive->value(), mid->value());
}
-
- if (repos[id]->isDeleted())
+ catch (const zypp::Exception& excpt)
{
- y2error("Source %zd has been deleted, the ID is not valid", id);
- return YRepo_Ptr();
+ _last_error.setLastError(ExceptionAsString(excpt));
+ y2milestone ("Directory not found: %s", d->value_cstr());
+ found = false;
}
-
- return repos[id];
- }
- catch (...)
- {
- y2error("Cannot find source with ID: %zd", id);
- // TODO: improve the error message
- _last_error.setLastError(_("Cannot find source"));
}
- // not found, return empty pointer
- return YRepo_Ptr();
-}
+ // set the original probing value
+ _silent_probing = _silent_probing_old;
-long long PkgModuleFunctions::logFindAlias(const std::string &alias) const
-{
- std::vector<YRepo_Ptr>::size_type index = 0;
+ CallDestDownload();
- for(std::vector<YRepo_Ptr>::const_iterator it = repos.begin(); it != repos.end() ; ++it, ++index)
+ if (found)
{
- if (!(*it)->isDeleted() && (*it)->repoInfo().alias() == alias)
- return index;
+ return YCPString(path.asString());
}
-
- return -1LL;
-}
-
-bool PkgModuleFunctions::aliasExists(const std::string &alias) const
-{
- for(std::vector<YRepo_Ptr>::const_iterator it = repos.begin(); it != repos.end() ; ++it)
+ else
{
- if (!(*it)->isDeleted() && (*it)->repoInfo().alias() == alias)
- return true;
+ return YCPVoid();
}
-
- return false;
-}
-
-/****************************************************************************************
- * @builtin SourceSetRamCache
- * @short Obsoleted function, do not use
- * @param boolean
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceSetRamCache (const YCPBoolean& a)
-{
- y2warning( "Pkg::SourceSetRamCache is obsolete and does nothing");
- return YCPBoolean( true );
}
/****************************************************************************************
- * @builtin SourceRestore
- *
- * @short Restore the sources from the persistent store
+ * @builtin SourceRefreshNow
+ * @short Attempt to immediately refresh a Source
* @description
- * Make sure the Source Manager is up and knows all available installation sources.
- * It's safe to call this multiple times, and once the installation sources are
- * actually enabled, it's even cheap
+ * The InsrSrc will be encouraged to check and refresh all metadata
+ * cached on disk.
+ *
+ * @param integer SrcId Specifies the InstSrc.
*
- * @return boolean True on success
+ * @return boolean
**/
YCPValue
-PkgModuleFunctions::SourceRestore()
+PkgModuleFunctions::SourceRefreshNow (const YCPInteger& id)
{
- if (repos.size() > 0)
- {
- y2warning("Number of registered repositories: %zd, skipping repository load!", repos.size());
- return YCPBoolean(true);
- }
-
- bool success = true;
+ YRepo_Ptr repo = logFindRepository(id->value());
+ if (!repo)
+ return YCPBoolean(false);
try
{
zypp::RepoManager repomanager = CreateRepoManager();
- std::list<zypp::RepoInfo> reps = repomanager.knownRepositories();
+ y2milestone("Refreshing metadata '%s'", repo->repoInfo().alias().c_str());
+ RefreshWithCallbacks(repo->repoInfo());
- repos.clear();
- for (std::list<zypp::RepoInfo>::iterator it = reps.begin();
- it != reps.end(); ++it)
- {
- repos.push_back(new YRepo(*it));
- }
+ y2milestone("Caching source '%s'...", repo->repoInfo().alias().c_str());
+ repomanager.buildCache(repo->repoInfo());
}
- catch (const zypp::Exception& excpt)
+ catch ( const zypp::Exception & expt )
{
- // FIXME: assuming the sources are already initialized
- y2error ("Error in SourceRestore: %s", excpt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- success = false;
+ y2error ("Error while refreshing the source: %s", expt.asString().c_str());
+ _last_error.setLastError(repo->repoInfo().alias() + ": " + ExceptionAsString(expt));
+ return YCPBoolean(false);
}
- return YCPBoolean(success);
-}
-
-/****************************************************************************************
- * @builtin SourceGetBrokenSources
- *
- * @short Return list of broken sources (sources which failed to restore)
- * @description
- * Get list of all sources which could not have been restored.
- * @return list<string> list of aliases (product names or URLs)
- **/
-YCPValue PkgModuleFunctions::SourceGetBrokenSources()
-{
- y2warning("Pkg::SourceGetBrokenSources() is obsoleted, it's not needed anymore.");
- return YCPList();
-}
-
-bool PkgModuleFunctions::SourceLoadReceiver(const zypp::ProgressData &progress)
-{
- y2milestone("Source Load receiver: %lld (%lld%%)", progress.val(), progress.reportValue());
-
- // get the YCP callback handler for destroy event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_ProcessProgress);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- ycp_handler->appendParameter(YCPInteger(progress.reportValue()));
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-
- return true;
-}
-
-/****************************************************************************************
- * @builtin SourceLoad
- *
- * @short Load resolvables from the installation sources
- * @description
- * Refresh the pool - Add/remove resolvables from the enabled/disabled sources.
- * @return boolean True on success
- **/
-YCPValue
-PkgModuleFunctions::SourceLoad()
-{
- std::list<std::string> stages;
- stages.push_back("Refresh Sources");
- stages.push_back("Rebuild Cache");
- stages.push_back("Load Data");
-
- PkgProgress pkgprogress(_callbackHandler);
-
- // 3 steps per repository (download, cache rebuild, load resolvables)
- pkgprogress.Start("Loading the Package Manager...", stages, "help");
-
- YCPValue ret = SourceLoadImpl(pkgprogress);
-
- pkgprogress.Done();
-
- return ret;
-}
-
-
-/****************************************************************************************
- * @builtin SourceLoad
- *
- * @short Load resolvables from the installation sources
- * @description
- * Refresh the pool - Add/remove resolvables from the enabled/disabled sources.
- * @return boolean True on success
- **/
-YCPValue
-PkgModuleFunctions::SourceLoadImpl(PkgProgress &progress)
-{
- bool success = true;
-
- int repos_to_load = 0;
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
- {
- repos_to_load++;
- }
- }
-
- // set max. value (3 steps per repository - refresh, rebuild, load)
- zypp::ProgressData prog_total(repos_to_load * 3);
- prog_total.sendTo(progress.Receiver());
-
- zypp::RepoManager repomanager = CreateRepoManager();
-
- // refresh metadata
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- // load resolvables only from enabled repos which are not deleted
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
- {
- // sub tasks
- zypp::CombinedProgressData refresh_subprogress(prog_total, 1);
-
- if (AnyResolvableFrom((*it)->repoInfo().alias()))
- {
- y2milestone("Resolvables from '%s' are already present, not loading", (*it)->repoInfo().alias().c_str());
- }
- else
- {
- // autorefresh the source
- if ((*it)->repoInfo().autorefresh())
- {
- try
- {
- y2milestone("Autorefreshing source: %s", (*it)->repoInfo().alias().c_str());
- RefreshWithCallbacks((*it)->repoInfo());
-
- zypp::ProgressData prog(1);
- prog.sendTo(refresh_subprogress);
- RefreshWithCallbacks((*it)->repoInfo());
- prog.toMax();
- }
- // NOTE: subtask progresses are reported as done in the descructor
- // no need to handle them in the exception code
- catch (const zypp::Exception& excpt)
- {
- y2error ("Error in SourceLoad: %s", excpt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- success = false;
- }
- }
- }
- }
- }
-
- progress.NextStage();
-
- // rebuild cache
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- // load resolvables only from enabled repos which are not deleted
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
- {
- // sub tasks
- zypp::CombinedProgressData rebuild_subprogress(prog_total, 1);
-
- if (AnyResolvableFrom((*it)->repoInfo().alias()))
- {
- y2milestone("Resolvables from '%s' are already present, not loading", (*it)->repoInfo().alias().c_str());
- }
- else
- {
- // autorefresh the source
- if ((*it)->repoInfo().autorefresh())
- {
- try
- {
- // rebuild cache (the default policy is "if needed")
- y2milestone("Rebuilding cache for '%s'...", (*it)->repoInfo().alias().c_str());
-
- zypp::ProgressData prog(1);
- prog.sendTo(rebuild_subprogress);
- repomanager.buildCache((*it)->repoInfo());
- prog.toMax();
- }
- // NOTE: subtask progresses are reported as done in the descructor
- // no need to handle them in the exception code
- catch (const zypp::Exception& excpt)
- {
- y2error ("Error in SourceLoad: %s", excpt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- success = false;
- }
- }
- }
- }
- }
-
- progress.NextStage();
-
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- // load resolvables only from enabled repos which are not deleted
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
- {
- // sub tasks
- zypp::CombinedProgressData load_subprogress(prog_total, 1);
-
- if (AnyResolvableFrom((*it)->repoInfo().alias()))
- {
- y2milestone("Resolvables from '%s' are already present, not loading", (*it)->repoInfo().alias().c_str());
- }
- else
- {
- zypp::ProgressData prog(1);
- prog.sendTo(load_subprogress);
-
- // load objects
- success = LoadResolvablesFrom((*it)->repoInfo()) && success;
-
- prog.toMax();
- }
- }
- }
-
- // report 100%
- prog_total.toMax();
-
- return YCPBoolean(success);
-}
-
-
-/****************************************************************************************
- * @builtin SourceStartManager
- *
- * @short Start the source manager - restore the sources and load the resolvables
- * @description
- * Calls SourceRestore(), if argument enable is true SourceLoad() is called.
- * @param boolean enable If true the resolvables are loaded from the enabled sources
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceStartManager (const YCPBoolean& enable)
-{
- PkgProgress pkgprogress(_callbackHandler);
-
- // display the progress only when 'enable' is true
- if (enable->value())
- {
- std::list<std::string> stages;
- stages.push_back("Load Sources");
- stages.push_back("Refresh Sources");
- stages.push_back("Rebuild Cache");
- stages.push_back("Load Data");
-
- // 3 steps per repository (download, cache rebuild, load resolvables)
- pkgprogress.Start("Loading the Package Manager...", stages, "help");
- }
-
- YCPValue ret = SourceStartManagerImpl(enable, pkgprogress);
-
- if (enable->value())
- {
- pkgprogress.Done();
- }
-
- return ret;
-}
-
-/****************************************************************************************
- * @builtin SourceStartManager
- *
- * @short Start the source manager - restore the sources and load the resolvables
- * @description
- * Calls SourceRestore(), if argument enable is true SourceLoad() is called.
- * @param boolean enable If true the resolvables are loaded from the enabled sources
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceStartManagerImpl(const YCPBoolean& enable, PkgProgress &progress)
-{
- YCPValue success = SourceRestore();
-
- progress.NextStage();
-
- if( enable->value() )
- {
- if (!success->asBoolean()->value())
- {
- y2warning("SourceStartManager: Some sources have not been restored, loading only the active sources...");
- }
-
- // enable all sources and load the resolvables
- success = YCPBoolean(SourceLoadImpl(progress)->asBoolean()->value() && success->asBoolean()->value());
- }
-
- return success;
-}
-
-/****************************************************************************************
- * @builtin SourceStartCache
- *
- * @short Make sure the InstSrcManager is up, and return the list of SrcIds.
- * @description
- * Make sure the InstSrcManager is up, and return the list of SrcIds.
- * In fact nothing more than:
- *
- * <code>
- * SourceStartManager( enabled_only );
- * return SourceGetCurrent( enabled_only );
- * </code>
- *
- * @param boolean enabled_only If true, make sure all InstSrces are enabled according to
- * their default, and return the Ids of enabled InstSrces only. If false, return
- * the Ids of all known InstSrces.
- *
- * @return list<integer> list of SrcIds
- **/
-YCPValue
-PkgModuleFunctions::SourceStartCache (const YCPBoolean& enabled)
-{
- try
- {
- SourceStartManager(enabled);
-
- return SourceGetCurrent(enabled);
- }
- catch (const zypp::Exception& excpt)
- {
- y2error ("Error in SourceStartCache: %s", excpt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- }
- // catch an exception from boost (e.g. a file cannot be read by non-root user)
- catch (const std::exception& err)
- {
- y2error ("Error in SourceStartCache: %s", err.what());
- _last_error.setLastError(err.what());
- }
- catch (...)
- {
- y2error("Unknown error in SourceStartCache");
- }
-
- return YCPList();
-}
-
-/****************************************************************************************
- * @builtin SourceCleanupBroken
- *
- * @short Clean up all sources that were not properly restored on the last
- * call of SourceStartManager or SourceStartCache.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceCleanupBroken ()
-{
- y2warning("Pkg::SourceCleanupBroken() is obsoleted, it's not needed anymore.");
- return YCPBoolean(true);
-}
-
-/****************************************************************************************
- * @builtin SourceGetCurrent
- *
- * @short Return the list of all InstSrc Ids.
- *
- * @param boolean enabled_only If true, or omitted, return the Ids of all enabled InstSrces.
- * If false, return the Ids of all known InstSrces.
- *
- * @return list<integer> list of SrcIds (integer)
- **/
-YCPValue
-PkgModuleFunctions::SourceGetCurrent (const YCPBoolean& enabled)
-{
- YCPList res;
-
- std::vector<YRepo_Ptr>::size_type index = 0;
- for( std::vector<YRepo_Ptr>::const_iterator it = repos.begin(); it != repos.end() ; ++it, ++index )
- {
- // ignore disabled sources if requested
- if (enabled->value())
- {
- // Note: enabled() is tribool!
- if ((*it)->repoInfo().enabled())
- {
- }
- else if (!(*it)->repoInfo().enabled())
- {
- continue;
- }
- else
- {
- continue;
- }
- }
-
- // ignore deleted sources
- if ((*it)->isDeleted())
- {
- continue;
- }
-
- res->add( YCPInteger(index) );
- }
-
- return res;
-}
-
-/****************************************************************************************
- * @builtin SourceReleaseAll
- *
- * @short Release all medias hold by all sources
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceReleaseAll ()
-{
- y2milestone("Releasing all sources...");
- bool ret = true;
-
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- try
- {
- (*it)->mediaAccess()->release();
- }
- catch (const zypp::media::MediaException & ex)
- {
- y2warning("Failed to release media for repo: %s", ex.msg().c_str());
- ret = false;
- }
- }
-
- return YCPBoolean(ret);
-}
-
-/******************************************************************************
- * @builtin SourceSaveAll
- *
- * @short Save all InstSrces.
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceSaveAll ()
-{
- y2milestone("Saving the source setup...");
-
- zypp::RepoManager repomanager = CreateRepoManager();
-
- // remove deleted repos (the old configurations) at first
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- // the repo has been removed
- if ((*it)->isDeleted())
- {
- std::string repo_alias = (*it)->repoInfo().alias();
-
- try
- {
- // remove the metadata
- zypp::RepoStatus raw_metadata_status = repomanager.metadataStatus((*it)->repoInfo());
- if (!raw_metadata_status.empty())
- {
- y2milestone("Removing metadata for source '%s'...", repo_alias.c_str());
- repomanager.cleanMetadata((*it)->repoInfo());
- }
-
- // remove the cache
- if (repomanager.isCached((*it)->repoInfo()))
- {
- y2milestone("Removing cache for '%s'...", repo_alias.c_str());
- repomanager.cleanCache((*it)->repoInfo());
- }
-
- repomanager.getRepositoryInfo(repo_alias);
- y2milestone("Removing repository '%s'", repo_alias.c_str());
- repomanager.removeRepository((*it)->repoInfo());
- }
- catch (const zypp::repo::RepoNotFoundException &ex)
- {
- // repository not found -- not critical, continue
- y2warning("No such repository: %s", repo_alias.c_str());
- }
- catch (const zypp::Exception & excpt)
- {
- y2error("Pkg::SourceSaveAll has failed: %s", excpt.msg().c_str() );
- _last_error.setLastError(ExceptionAsString(excpt));
- return YCPBoolean(false);
- }
- }
- }
-
- // save all repos (the current configuration)
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- if (!(*it)->isDeleted())
- {
- std::string current_alias = (*it)->repoInfo().alias();
-
- try
- {
- try
- {
- // if the repository already exists then just modify it
- repomanager.getRepositoryInfo(current_alias);
- y2milestone("Modifying repository '%s'", current_alias.c_str());
- repomanager.modifyRepository(current_alias, (*it)->repoInfo());
- }
- catch (const zypp::repo::RepoNotFoundException &ex)
- {
- // the repository was not found, add it
- y2milestone("Adding repository '%s'", current_alias.c_str());
- repomanager.addRepository((*it)->repoInfo());
- }
- }
- catch (zypp::Exception & excpt)
- {
- y2error("Pkg::SourceSaveAll has failed: %s", excpt.msg().c_str() );
- _last_error.setLastError(ExceptionAsString(excpt));
- return YCPBoolean(false);
- }
- }
- }
-
- y2milestone("All sources have been saved");
-
- return YCPBoolean(true);
-}
-
-/****************************************************************************************
- * @builtin SourceFinishAll
- *
- * @short Save and then disable all InstSrces.
- * @description
- * If there are no enabled sources, do nothing
- * (idempotence hack, broken design: #155459, #176013, use SourceSaveAll).
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceFinishAll ()
-{
- try
- {
- bool found_enabled = false;
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
- {
- found_enabled = true;
- break;
- }
- }
-
- if (!found_enabled)
- {
- y2milestone( "No enabled sources, skipping SourceFinishAll()" );
- return YCPBoolean( true );
- }
-
- SourceSaveAll();
-
- y2milestone( "Disabling all sources...") ;
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- (*it)->repoInfo().setEnabled(false);
- }
- // TODO FIXME remove all resolvables??
- }
- catch (zypp::Exception & excpt)
- {
- y2error("Pkg::SourceFinishAll has failed: %s", excpt.msg().c_str() );
- _last_error.setLastError(ExceptionAsString(excpt));
- return YCPBoolean(false);
- }
-
- y2milestone("All sources have been saved and disabled");
-
- return YCPBoolean(true);
-}
-
-/////////////////////////////////////////////////////////////////////////////////////////
-// Query individual sources
-/////////////////////////////////////////////////////////////////////////////////////////
-
-/****************************************************************************************
- * @builtin SourceGeneralData
- *
- * @short Get general data about the source
- * @description
- * Return general data about the source as a map:
- *
- * <code>
- * $[
- * "enabled" : YCPBoolean,
- * "autorefresh": YCPBoolean,
- * "product_dir": YCPString,
- * "type" : YCPString,
- * "url" : YCPString (without password, but see SourceURL),
- * "alias" : YCPString,
- * "name" : YCPString,
- * ];
- *
- * </code>
- * @param integer SrcId Specifies the InstSrc to query.
- * @return map
- **/
-YCPValue
-PkgModuleFunctions::SourceGeneralData (const YCPInteger& id)
-{
- YCPMap data;
-
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPVoid ();
-
- // convert type to the old strings ("YaST", "YUM" or "Plaindir")
- std::string srctype = zypp2yastType(repo->repoInfo().type().asString());
-
- data->add( YCPString("enabled"), YCPBoolean(repo->repoInfo().enabled()));
- data->add( YCPString("autorefresh"), YCPBoolean(repo->repoInfo().autorefresh()));
- data->add( YCPString("type"), YCPString(srctype));
- data->add( YCPString("product_dir"), YCPString(repo->repoInfo().path().asString()));
-
- // check if there is an URL
- if (repo->repoInfo().baseUrlsBegin() != repo->repoInfo().baseUrlsEnd())
- {
- data->add( YCPString("url"), YCPString(repo->repoInfo().baseUrlsBegin()->asString()));
- }
-
- data->add( YCPString("alias"), YCPString(repo->repoInfo().alias()));
- data->add( YCPString("name"), YCPString(repo->repoInfo().name()));
-
- YCPList base_urls;
- for( zypp::RepoInfo::urls_const_iterator it = repo->repoInfo().baseUrlsBegin(); it != repo->repoInfo().baseUrlsEnd(); ++it)
- {
- base_urls->add(YCPString(it->asString()));
- }
- data->add( YCPString("base_urls"), base_urls);
-
- data->add( YCPString("mirror_list"), YCPString(repo->repoInfo().mirrorListUrl().asString()));
-
- return data;
-}
-
-/******************************************************************************
- * @builtin SourceURL
- *
- * @short Get full source URL, including password
- * @param integer SrcId Specifies the InstSrc to query.
- * @return string or nil on failure
- **/
-YCPValue
-PkgModuleFunctions::SourceURL (const YCPInteger& id)
-{
-
- const YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPVoid();
-
- std::string url;
-
- if (repo->repoInfo().baseUrlsBegin() != repo->repoInfo().baseUrlsEnd())
- {
- // #186842
- url = repo->repoInfo().baseUrlsBegin()->asCompleteString();
- }
-
- return YCPString(url);
-}
-
-/****************************************************************************************
- * @builtin SourceMediaData
- * @short Return media data about the source
- * @description
- * Return media data about the source as a map:
- *
- * <code>
- * $["media_count": YCPInteger,
- * "media_id" : YCPString,
- * "media_vendor" : YCPString,
- * "url" : YCPString,
- * ];
- * </code>
- *
- * @param integer SrcId Specifies the InstSrc to query.
- * @return map
- **/
-YCPValue
-PkgModuleFunctions::SourceMediaData (const YCPInteger& id)
-{
- YCPMap data;
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPVoid ();
-
- std::string alias = repo->repoInfo().alias();
- bool found_resolvable = false;
- int max_medium = 1;
-
- for (zypp::ResPool::const_iterator it = zypp_ptr()->pool().begin()
- ; it != zypp_ptr()->pool().end()
- ; ++it)
- {
- if (it->resolvable()->repository().info().alias() == alias)
- {
- int medium = it->resolvable()->mediaNr();
-
- if (medium > max_medium)
- {
- max_medium = medium;
- }
- }
- }
-
- if (found_resolvable)
- {
- data->add( YCPString("media_count"), YCPInteger(max_medium));
- }
- else
- {
- y2error("No resolvable from repository '%s' found, cannot get number of media (use Pkg::SourceLoad() to load the resolvables)", alias.c_str());
- }
-
- y2warning("Pkg::SourceMediaData() doesn't return \"media_id\" and \"media_vendor\" values anymore.");
-
- // SourceMediaData returns URLs without password
- if (repo->repoInfo().baseUrlsBegin() != repo->repoInfo().baseUrlsEnd())
- {
- data->add( YCPString("url"), YCPString(repo->repoInfo().baseUrlsBegin()->asString()));
-
- // add all base URLs
- YCPList base_urls;
- for( zypp::RepoInfo::urls_const_iterator it = repo->repoInfo().baseUrlsBegin(); it != repo->repoInfo().baseUrlsEnd(); ++it)
- {
- base_urls->add(YCPString(it->asString()));
- }
- data->add( YCPString("base_urls"), base_urls);
- }
-
- return data;
-}
-
-/****************************************************************************************
- * @builtin SourceProductData
- * @short Return Product data about the source
- * @param integer SrcId Specifies the InstSrc to query.
- * @description
- * Product data about the source as a map:
- *
- * <code>
- * $[
- * "label" : YCPString,
- * "vendor" : YCPString,
- * "productname" : YCPString,
- * "productversion" : YCPString,
- * "relnotesurl" : YCPString,
- * ];
- * </code>
- *
- * @return map
- **/
-YCPValue
-PkgModuleFunctions::SourceProductData (const YCPInteger& src_id)
-{
- YCPMap ret;
-
- try
- {
- // find a product for the given source
- zypp::ResPool::byKind_iterator it = zypp_ptr()->pool().byKindBegin(zypp::ResTraits<zypp::Product>::kind);
-
- for( ; it != zypp_ptr()->pool().byKindEnd(zypp::ResTraits<zypp::Product>::kind) ; ++it)
- {
- zypp::Product::constPtr product = boost::dynamic_pointer_cast<const zypp::Product>( it->resolvable() );
-
- if( logFindAlias(product->repository().info().alias()) == src_id->value() )
- {
- ret->add( YCPString("label"), YCPString( product->summary() ) );
- ret->add( YCPString("vendor"), YCPString( product->vendor() ) );
- ret->add( YCPString("productname"), YCPString( product->name() ) );
- ret->add( YCPString("productversion"), YCPString( product->edition().version() ) );
- ret->add( YCPString("relnotesurl"), YCPString( product->releaseNotesUrl().asString()));
-
- #warning SourceProductData not finished
- /*
- data->add( YCPString("datadir"), YCPString( descr->content_datadir().asString() ) );
- TODO (?): "baseproductname", "baseproductversion", "defaultbase", "architectures",
- "requires", "linguas", "labelmap", "language", "timezone", "descrdir", "datadir"
- */
-
- break;
- }
- }
-
- if( it == zypp_ptr()->pool().byKindEnd(zypp::ResTraits<zypp::Product>::kind) )
- {
- y2error ("Product for source '%lld' not found", src_id->value());
- }
- }
- catch (...)
- {
- }
-
- return ret;
-}
-
-/****************************************************************************************
- * @builtin SourceProduct
- * @short Obsoleted function, do not use, see SourceProductData builtin
- * @deprecated
- * @param integer
- * @return map empty map
- **/
-YCPValue
-PkgModuleFunctions::SourceProduct (const YCPInteger& id)
-{
- /* TODO FIXME */
- y2error("Pkg::SourceProduct() is obsoleted, use Pkg::SourceProductData() instead!");
- return YCPMap();
-}
-
-
-YCPValue PkgModuleFunctions::SourceProvideFileCommon(const YCPInteger &id,
- const YCPInteger &mid,
- const YCPString& f,
- const YCPBoolean & optional)
-{
- CallInitDownload(std::string(_("Downloading ") + f->value()));
-
- bool found = true;
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- found = false;
-
- extern ZyppRecipients::MediaChangeSensitivity _silent_probing;
- // remember the current value
- ZyppRecipients::MediaChangeSensitivity _silent_probing_old = _silent_probing;
-
- // disable media change callback for optional file
- if (optional->value())
- _silent_probing = ZyppRecipients::MEDIA_CHANGE_OPTIONALFILE;
-
- zypp::filesystem::Pathname path; // FIXME use ManagedMedia
- if (found)
- {
- try
- {
- path = repo->mediaAccess()->provideFile(f->value(), mid->value());
- y2milestone("local path: '%s'", path.asString().c_str());
- }
- catch (const zypp::Exception& excpt)
- {
- found = false;
-
- if (!optional->value())
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2milestone("File not found: %s", f->value_cstr());
- }
- }
- }
-
- // set the original probing value
- _silent_probing = _silent_probing_old;
-
- CallDestDownload();
-
- if (found)
- {
- return YCPString(path.asString());
- }
- else
- {
- return YCPVoid();
- }
-}
-
-
-/****************************************************************************************
- * @builtin SourceProvideFile
- *
- * @short Make a file available at the local filesystem
- * @description
- * Let an InstSrc provide some file (make it available at the local filesystem).
- *
- * @param integer SrcId Specifies the InstSrc .
- * @param integer medianr Number of the media the file is located on ('1' for the 1st media).
- * @param string file Filename relative to the media root.
- *
- * @return string local path as string
- **/
-YCPValue
-PkgModuleFunctions::SourceProvideFile (const YCPInteger& id, const YCPInteger& mid, const YCPString& f)
-{
- return SourceProvideFileCommon(id, mid, f, false /*optional*/);
-}
-
-/****************************************************************************************
- * @builtin SourceProvideOptionalFile
- *
- * @short Make an optional file available at the local filesystem
- * @description
- * Let an InstSrc provide some file (make it available at the local filesystem).
- * If the file doesn't exist don't ask user for another medium and return nil
- *
- * @param integer SrcId Specifies the InstSrc .
- * @param integer medianr Number of the media the file is located on ('1' for the 1st media).
- * @param string file Filename relative to the media root.
- *
- * @return string local path as string
- **/
-YCPValue
-PkgModuleFunctions::SourceProvideOptionalFile (const YCPInteger& id, const YCPInteger& mid, const YCPString& f)
-{
- return SourceProvideFileCommon(id, mid, f, true /*optional*/);
-}
-
-/****************************************************************************************
- * @builtin SourceProvideDir
- * @short make a directory available at the local filesystem
- * @description
- * Let an InstSrc provide some directory (make it available at the local filesystem) and
- * all the files within it (non recursive).
- *
- * @param integer SrcId Specifies the InstSrc .
- * @param integer medianr Number of the media the file is located on ('1' for the 1st media).
- * @param string dir Directoryname relative to the media root.
- * @return string local path as string
- */
-YCPValue
-PkgModuleFunctions::SourceProvideDir (const YCPInteger& id, const YCPInteger& mid, const YCPString& d)
-{
- y2warning("Pkg::SourceProvideDir() is obsoleted use Pkg::SourceProvideDirectory() instead");
- // non optional, non recursive
- return SourceProvideDirectory(id, mid, d, false, false);
-}
-
-
-/****************************************************************************************
- * @builtin SourceProvideDirectory
- * @short make a directory available at the local filesystem
- * @description
- * Download a directory from repository (make it available at the local filesystem) and
- * all the files within it.
- *
- * @param integer id repository to use (id)
- * @param integer mid Number of the media where the directory is located on ('1' for the 1st media).
- * @param string d Directory name relative to the media root.
- * @param boolean optional set to true if the directory may not exist (do not report errors)
- * @param boolean recursive set to true to provide all subdirectories recursively
- * @return string local path as string or nil when an error occured
- */
-YCPValue
-PkgModuleFunctions::SourceProvideDirectory(const YCPInteger& id, const YCPInteger& mid, const YCPString& d, const YCPBoolean &optional, const YCPBoolean &recursive)
-{
- CallInitDownload(std::string(_("Downloading ") + d->value()));
-
- bool found = true;
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- found = false;
-
- zypp::filesystem::Pathname path; // FIXME user ManagedMedia
-
- extern ZyppRecipients::MediaChangeSensitivity _silent_probing;
- // remember the current value
- ZyppRecipients::MediaChangeSensitivity _silent_probing_old = _silent_probing;
-
- // disable media change callback for optional file
- if (optional->value())
- _silent_probing = ZyppRecipients::MEDIA_CHANGE_OPTIONALFILE;
-
- if (found)
- {
- try
- {
- path = repo->mediaAccess()->provideDir(d->value(), recursive->value(), mid->value());
- }
- catch (const zypp::Exception& excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2milestone ("Directory not found: %s", d->value_cstr());
- found = false;
- }
- }
-
- // set the original probing value
- _silent_probing = _silent_probing_old;
-
- CallDestDownload();
-
- if (found)
- {
- return YCPString(path.asString());
- }
- else
- {
- return YCPVoid();
- }
-}
-
-/****************************************************************************************
- * @builtin SourceChangeUrl
- * @short Change Source URL
- * @description
- * Change url of an InstSrc. Used primarely when re-starting during installation
- * and a cd-device changed from hdX to srX since ide-scsi was activated.
- * @param integer SrcId Specifies the InstSrc.
- * @param string url The new url to use.
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceChangeUrl (const YCPInteger& id, const YCPString& u)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- try
- {
- if (repo->repoInfo().baseUrlsSize() > 1)
- {
- // store current urls
- std::set<zypp::Url> baseUrls (repo->repoInfo().baseUrlsBegin(), repo->repoInfo().baseUrlsEnd());
-
- // reset url list and store the new one there
- repo->repoInfo().setBaseUrl(zypp::Url(u->value()));
-
- // add the rest of base urls
- for (std::set<zypp::Url>::const_iterator i = baseUrls.begin();
- i != baseUrls.end(); ++i)
- repo->repoInfo().addBaseUrl(*i);
- }
- else
- repo->repoInfo().setBaseUrl(zypp::Url(u->value()));
- }
- catch (const zypp::Exception & excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error ("Cannot set the new URL for source %s (%lld): %s",
- repo->repoInfo().alias().c_str(), id->asInteger()->value(), excpt.msg().c_str());
- return YCPBoolean(false);
- }
-
- return YCPBoolean(true);
-}
-
-/****************************************************************************************
- * @builtin SourceInstallOrder
- *
- * @short not implemented, do not use (Explicitly set an install order.)
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceInstallOrder (const YCPMap& ord)
-{
- /* TODO FIXME
- YCPList args;
- args->add (ord);
-
- //-------------------------------------------------------------------------------------//
- YcpArgLoad decl(__FUNCTION__);
-
- YCPMap & order_map( decl.arg<YT_MAP, YCPMap>() );
-
- if ( ! decl.load( args ) ) {
- return pkgError_bad_args;
- }
- //-------------------------------------------------------------------------------------//
-
- InstSrcManager::InstOrder order;
- order.reserve( order_map->size() );
- bool error = false;
-
- for ( YCPMapIterator it = order_map->begin(); it != order_map->end(); ++it ) {
-
- if ( it.value()->isInteger() ) {
- InstSrc::UniqueID uId( it.value()->asInteger()->value() );
- InstSrcManager::ISrcId source_id( _y2pm.instSrcManager().getSourceByID( uId ) );
- if ( source_id ) {
- if ( source_id->enabled() ) {
- order.push_back( uId ); // finaly ;)
-
- } else {
- y2error ("order map entry '%s:%s': source not enabled",
- it.key()->toString().c_str(),
- it.value()->toString().c_str() );
- error = true;
- }
- } else {
- y2error ("order map entry '%s:%s': bad source id",
- it.key()->toString().c_str(),
- it.value()->toString().c_str() );
- error = true;
- }
- } else {
- y2error ("order map entry '%s:%s': integer value expected",
- it.key()->toString().c_str(),
- it.value()->toString().c_str() );
- error = true;
- }
- }
- if ( error ) {
- return pkgError( Error::E_bad_args );
- }
-
- // store new instorder
- _y2pm.instSrcManager().setInstOrder( order );
-*/
-
-#warning SourceInstallOrder is not implemented
- return YCPBoolean( true );
-}
-
-
-static std::string timestamp ()
-{
- time_t t = time(NULL);
- struct tm * tmp = localtime(&t);
-
- if (tmp == NULL) {
- return "";
- }
-
- char outstr[50];
- if (strftime(outstr, sizeof(outstr), "%Y%m%d-%H%M%S", tmp) == 0) {
- return "";
- }
- return outstr;
-}
-
-/**
- * Take the ?alias=foo part of old_url, if any, and return it,
- * putting the rest to new_url.
- * \throws Exception on malformed URLs I guess
- */
-static std::string removeAlias (const zypp::Url & old_url,
- zypp::Url & new_url)
-{
- std::string alias;
- new_url = old_url;
- zypp::url::ParamMap query = new_url.getQueryStringMap ();
- zypp::url::ParamMap::iterator alias_it = query.find ("alias");
- if (alias_it != query.end ())
- {
- alias = alias_it->second;
- query.erase (alias_it);
- new_url.setQueryStringMap (query);
- }
- return alias;
-}
-
-std::string PkgModuleFunctions::UniqueAlias(const std::string &alias)
-{
- // make a copy
- std::string ret = alias;
-
- unsigned int id = 0;
- while(aliasExists(ret))
- {
- y2milestone("Alias %s already found: %lld", ret.c_str(), logFindAlias(ret));
-
- // the alias already exists - add a counter
- std::ostringstream ostr;
- ostr << alias << "_" << id;
-
- ret = ostr.str();
-
- y2milestone("Using alias %s", ret.c_str());
- ++id;
- }
-
- return ret;
-}
-
-
-/**
- * helper - add "mountoptions=ro" for mountable URL schemes if "mountoptions" option is not empty and
- * "rw" or "ro" option is missing
- */
-zypp::Url addRO(const zypp::Url &url)
-{
- zypp::Url ret(url);
- std::string scheme = zypp::str::toLower(url.getScheme());
-
- if (scheme == "nfs"
- || scheme == "hd"
- || scheme == "smb"
- || scheme == "iso"
- || scheme == "cd"
- || scheme == "dvd"
- )
- {
- const std::string mountoptions = "mountoptions";
- zypp::media::Mount::Options options(url.getQueryParam(mountoptions));
-
- y2debug("Current mountoptions: %s", options.asString().c_str());
-
- // if mountoptions are empty lizypp uses "ro" by default
- // don't override "rw" option from application
- // don't add "ro" if it's already present
- if (!options.empty() && !options.has("rw") && !options.has("ro"))
- {
- options["ro"];
-
- ret.setQueryParam(mountoptions, options.asString());
- y2milestone("Adding read only mount option: '%s' -> '%s'", url.asString().c_str(), ret.asString().c_str());
- }
- }
-
- return ret;
-}
-
-// helper function
-zypp::Url PkgModuleFunctions::shortenUrl(const zypp::Url &url)
-{
- std::string url_path = url.getPathName();
- std::string begin_path;
- std::string end_path;
-
- // try to convert 'http://server/dir1/dir2/dir3/dir4' -> 'http://server/dir1/.../dir4'
- std::string::size_type pos_first = url_path.find("/");
- if (pos_first == 0)
- {
- pos_first = url_path.find("/", 1);
- }
-
- if (pos_first == std::string::npos)
- {
- const int num = 5;
-
- // "/" not found use the beginning and the end part
- // 'http://server/very_long_directory_name' -> 'http://server/very_..._name'
- begin_path = std::string(url_path, 0, num);
- end_path = std::string(url_path, url_path.size() - num - 1, num);
- }
- else
- {
- unsigned int pos_last = url_path.rfind("/");
- if (pos_last == url_path.size() - 1)
- {
- pos_last = url_path.rfind("/", url_path.size() - 1);
- }
-
- if (pos_last == pos_first || pos_last < pos_first)
- {
- const int num = 5;
-
- // "/" not found use the beginning and the end part
- begin_path = std::string(url_path, 0, num);
- end_path = std::string(url_path, url_path.size() - num - 1, num);
- }
- else
- {
- begin_path = std::string(url_path, 0, pos_first + 1);
- end_path = std::string(url_path, pos_last);
- }
- }
-
- std::string new_path = begin_path + "..." + end_path;
- zypp::Url ret(url);
-
- // use the shorter path
- ret.setPathName(new_path);
- // remove query parameters
- ret.setQueryString("");
- // remove fragmet
- ret.setFragment("");
-
- y2milestone("Using shortened URL: '%s' -> '%s'", url.asString().c_str(), ret.asString().c_str());
- return ret;
-}
-
-/** Create a Source and immediately put it into the SourceManager.
- * \return the SourceId
- * \throws Exception if Source creation fails
-*/
-std::vector<zypp::RepoInfo>::size_type
-PkgModuleFunctions::createManagedSource( const zypp::Url & url_r,
- const zypp::Pathname & path_r,
- const bool base_source,
- const std::string& type,
- const std::string &alias_r )
-{
- // parse URL
- y2milestone ("Original URL: %s, product directory: %s", url_r.asString().c_str(), path_r.asString().c_str());
-
- // #158850#c17, if the URL contains an alias, we use that
- zypp::Url url;
-
- std::string alias = removeAlias(url_r, url);
- y2milestone("Alias from URL: '%s'", alias.c_str());
-
-#warning FIXME: use base_source (base_source vs. addon) (will be probably not needed)
-
- // repository type
- zypp::repo::RepoType repotype;
- zypp::RepoManager repomanager = CreateRepoManager();
-
- if (!type.empty())
- {
- try
- {
- // do conversion from the Yast type ("YaST", "YUM", "Plaindir")
- // to libzypp type ("yast", "yum", "plaindir")
- repotype = repotype.parse(yast2zyppType(type));
- }
- catch (zypp::repo::RepoUnknownTypeException &e)
- {
- y2warning("Unknown source type '%s'", type.c_str());
- }
- }
-
- // the type is not specified or is wrong, autoprobe the type
- if (repotype == zypp::repo::RepoType::NONE)
- {
- zypp::Url probe_url(url_r);
-
- if (!path_r.asString().empty())
- {
- zypp::Pathname pth(probe_url.getPathName());
- pth /= path_r;
-
- probe_url.setPathName(pth.asString());
- }
-
- y2milestone("Probing source type: '%s'", probe_url.asString().c_str());
-
- // autoprobe type of the repository
- repotype = ProbeWithCallbacks(probe_url);
- }
-
- y2milestone("Using source type: %s", repotype.asString().c_str());
-
-
- // create source definition object
- zypp::RepoInfo repo;
-
- std::string name;
-
- // set alias and name
- if (alias.empty())
- {
- // alias not set via URL, use the passed alias or the URL path
- if (alias_r.empty())
- {
- // use the last path element in URL
- std::string url_path = url.getPathName();
-
- std::string::size_type pos_begin = url_path.rfind("/");
- std::string::size_type pos_end = std::string::npos;
-
- // ignore the trailing slash
- if (pos_begin == url_path.size() - 1)
- {
- pos_begin = url_path.rfind("/", url_path.size() - 2);
-
- if (pos_begin != std::string::npos)
- {
- pos_end = url_path.size() - pos_begin - 2;
- }
- }
- else
- {
- pos_end = url_path.size() - pos_begin - 1;
- }
-
- // ignore the found slash character
- pos_begin++;
-
- alias = std::string(url_path, pos_begin, pos_end);
-
- y2milestone("Alias from URL path: %s", alias.c_str());
-
- // fallback
- if (alias.empty())
- {
- y2milestone("URL alias is empty using 'Repository'");
- alias = "Repository";
- }
- }
- else
- {
- alias = alias_r;
- }
-
- name = alias;
- }
- else
- {
- name = alias;
- }
-
-
- y2milestone("Name of the repository: '%s'", name.c_str());
-
- // alias must be unique, add a suffix if it's already used
- alias = UniqueAlias(alias);
-
- // add read only mount option to the URL if needed
- url = addRO(url);
-
- bool autorefresh = true;
-
- std::string scheme = zypp::str::toLower(url.getScheme());
- if (scheme == "cd" || scheme == "dvd")
- {
- y2milestone("Disabling autorefresh for CD/DVD repository");
- autorefresh = false;
- }
-
- repo.setAlias(alias);
- repo.setName(name);
- repo.setType(repotype);
- repo.addBaseUrl(url);
- repo.setPath(path_r);
- repo.setEnabled(true);
- repo.setAutorefresh(autorefresh);
-
- // set metadata path (#293428)
- zypp::Pathname metadatapath = repomanager.metadataPath(repo);
- repo.setMetadataPath(metadatapath);
-
- y2milestone("Adding source '%s' (%s, dir: %s)", repo.alias().c_str(), url.asString().c_str(), path_r.asString().c_str());
- // note: exceptions should be caught by the calling code
- RefreshWithCallbacks(repo);
-
- // build cache if needed
- if (!repomanager.isCached(repo))
- {
- y2milestone("Caching source '%s'...", repo.alias().c_str());
- repomanager.buildCache(repo);
- }
-
- repos.push_back(new YRepo(repo));
-
- y2milestone("Added source '%s': '%s', enabled: %s, autorefresh: %s",
- repo.alias().c_str(),
- repo.baseUrlsBegin()->asString().c_str(),
- repo.enabled() ? "true" : "false",
- repo.autorefresh() ? "true" : "false"
- );
-
- // the source is at the end of the list
- return repos.size() - 1;
-}
-
-/****************************************************************************************
- * @builtin RepositoryAdd
- *
- * @short Register a new repository
- * @description
- * Adds a new repository to the internal structures. The repository is only registered,
- * metadata is not downloaded, use Pkg::SourceRefreshNow() for that. The metadata is also loaded
- * automatically when loading the repository content (Pkg::SourceLoad())
- *
- * @param map map with repository parameters: $[ "enabled" : boolean, "autorefresh" : boolean, "name" : string,
- * "alias" : string, "base_urls" : list<string>, "prod_dir" : string, "type" : string ]
- * @return integer Repository ID or nil on error
- **/
-YCPValue PkgModuleFunctions::RepositoryAdd(const YCPMap ¶ms)
-{
- zypp::RepoInfo repo;
-
- // turn on the repo by default
- repo.setEnabled(true);
- // enable autorefresh by default
- repo.setAutorefresh(true);
-
- if (!params->value( YCPString("enabled") ).isNull() && params->value(YCPString("enabled"))->isBoolean())
- {
- repo.setEnabled(params->value(YCPString("enabled"))->asBoolean()->value());
- }
-
- if (!params->value( YCPString("autorefresh") ).isNull() && params->value(YCPString("autorefresh"))->isBoolean())
- {
- repo.setAutorefresh(params->value(YCPString("autorefresh"))->asBoolean()->value());
- }
-
- std::string alias;
-
- if (!params->value( YCPString("alias") ).isNull() && params->value(YCPString("alias"))->isString())
- {
- alias = params->value(YCPString("alias"))->asString()->value();
- }
-
- if (alias.empty())
- {
- alias = timestamp();
-
- // the alias must be unique
- alias = UniqueAlias(alias);
- }
- else
- {
- if (aliasExists(alias))
- {
- ycperror("alias %s already exists", alias.c_str());
- return YCPVoid();
- }
- }
-
- repo.setAlias(alias);
-
- // use the first base URL as a fallback name
- std::string first_url;
-
- if (!params->value( YCPString("base_urls") ).isNull() && params->value(YCPString("base_urls"))->isList())
- {
- YCPList lst(params->value(YCPString("base_urls"))->asList());
-
- for (int index = 0; index < lst->size(); ++index)
- {
- if( ! lst->value(index)->isString() )
- {
- ycperror( "Pkg::RepositoryAdd(): entry not a string at index %d: %s", index, lst->toString().c_str());
- return YCPVoid();
- }
-
- zypp::Url url;
-
- try
- {
- url = lst->value(index)->asString()->value();
- zypp::Url url_new;
-
- std::string name = removeAlias(url, url_new);
-
- if (!name.empty())
- {
- repo.setName(name);
- url = url_new;
- }
-
- // add read only mount option to the URL if needed
- url = addRO(url);
- }
- catch(const zypp::Exception & expt)
- {
- y2error("Invalid URL: %s", expt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(expt));
- return YCPVoid();
- }
-
- if (index == 0)
- {
- first_url = url.asString();
- }
-
- repo.addBaseUrl(url);
- }
- }
- else
- {
- ycperror("Missing \"base_urls\" key in the map");
- return YCPVoid();
- }
-
- // check name parameter
- if (!params->value( YCPString("name") ).isNull() && params->value(YCPString("name"))->isString())
- {
- repo.setName(params->value(YCPString("name"))->asString()->value());
- }
- else
- {
- // if the key "name" is missing and the name hasn't been set by ?alias= in the URL
- // then use the first URL as the name
- if (repo.name().empty())
- {
- repo.setName(first_url);
- }
- }
-
- if (!params->value( YCPString("type") ).isNull() && params->value(YCPString("type"))->isString())
- {
- std::string type = yast2zyppType(params->value(YCPString("type"))->asString()->value());
-
- try
- {
- zypp::repo::RepoType repotype(type);
- repo.setType(repotype);
- }
- catch (zypp::repo::RepoUnknownTypeException &e)
- {
- ycperror("Unknown source type '%s': %s", type.c_str(), e.asString().c_str());
- _last_error.setLastError(ExceptionAsString(e));
- return YCPVoid();
- }
-
- }
-
- if (!params->value( YCPString("prod_dir") ).isNull() && params->value(YCPString("prod_dir"))->isString())
- {
- repo.setPath(params->value(YCPString("prod_dir"))->asString()->value());
- }
-
- // set metadata path (#293428)
- zypp::RepoManager repomanager = CreateRepoManager();
- zypp::Pathname metadatapath = repomanager.metadataPath(repo);
- repo.setMetadataPath(metadatapath);
-
- repos.push_back(new YRepo(repo));
-
- // the new source is at the end of the list
- return YCPInteger(repos.size() - 1);
-}
-
-/****************************************************************************************
- * @builtin SourceCacheCopyTo
- *
- * @short Copy cache data of all installation sources to the target
- * @description
- * Copy cache data of all installation sources to the target located below 'dir'.
- * To be called at end of initial installation.
- *
- * @param string dir Root directory of target.
- * @return boolean true on success
- **/
-YCPValue
-PkgModuleFunctions::SourceCacheCopyTo (const YCPString& dir)
-{
- // error message (followed by detailed description)
- const std::string msg = _("Error: Cannot copy the cache to the target directory\n");
-
- std::string d = dir->value();
- y2milestone("Copying source cache to '%s'...", d.c_str());
-
- if (d.empty())
- {
- y2error("Empty parameter in Pkg::SourceCacheCopyTo()!");
- return YCPBoolean(false);
- }
-
- std::string target = d + "/var/cache";
-
- // create the target dir
- const char* argv[] =
- {
- "mkdir",
- // create parent dir
- "-p",
- // finish parameter list
- "--",
- // target
- target.c_str(),
- NULL
- };
-
- // discard stderr, no pty, stderr_fd = -1, use the default locale
- zypp::ExternalProgram prog(argv, zypp::ExternalProgram::Discard_Stderr, false, -1, true);
-
- int code = prog.close();
-
- if (code)
- {
- // error message (followed by directory name)
- _last_error.setLastError(msg + _("Cannot create directory ") + target);
- y2error("Cannot create target directory %s", target.c_str());
- return YCPBoolean(false);
- }
-
- // copy /var/cache/zypp to the target system
- const char* argv2[] =
- {
- "cp",
- // preserve time stamps
- "-a",
- // recursive
- "-r",
- // finish parameter list
- "--",
- // source
- "/var/cache/zypp",
- // target
- target.c_str(),
- NULL
- };
-
- // discard stderr, no pty, stderr_fd = -1, use the default locale
- zypp::ExternalProgram prog2(argv2, zypp::ExternalProgram::Discard_Stderr, false, -1, true);
-
- int code2 = prog2.close();
-
- if (code2)
- {
- // error message
- _last_error.setLastError(msg + _("Copying failed"));
- y2error("Cannot copy /var/cache/zypp to %s", d.c_str());
- }
-
- return YCPBoolean(!code2);
-}
-
-/****************************************************************************************
- * @builtin SourceScan
- * @short Scan a Source Media
- * @description
- * Load all InstSrces found at media_url, i.e. all sources mentioned in /media.1/products.
- * If no /media.1/products is available, InstSrc is expected to be located directly
- * below media_url (product_dir: /).
- *
- * If a product_dir is provided, only the InstSrc located at media_url/product_dir is loaded.
- *
- * In contrary to @ref SourceCreate, InstSrces are loaded into the InstSrcManager,
- * but not enabled (packages and selections are not provided to the PackageManager),
- * and the SrcIds of <b>all</b> InstSrces found are returned.
- *
- * @param string url The media to scan.
- * @optarg string product_dir Restrict scan to a certain InstSrc located in media_url/product_dir.
- *
- * @return list<integer> list of SrcIds (integer).
- **/
-YCPValue
-PkgModuleFunctions::SourceScan (const YCPString& media, const YCPString& pd)
-{
- zypp::Url url;
-
- try {
- url = zypp::Url(media->value ());
- }
- catch(const zypp::Exception & expt )
- {
- y2error ("Invalid URL: %s", expt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(expt));
- return YCPList();
- }
-
- zypp::Pathname pn(pd->value ());
-
- YCPList ids;
- std::vector<zypp::RepoInfo>::size_type id;
-
- if ( pd->value().empty() ) {
-
- // scan all sources
- zypp::MediaProductSet products;
-
- try
- {
- y2milestone("Scanning products in %s ...", url.asString().c_str());
- ScanProductsWithCallBacks(url);
- products = available_products;
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("Scanning products for '%s' has failed"
- , url.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- return ids;
- }
-
- if( products.empty() )
- {
- // no products found, use the base URL instead
- zypp::MediaProductEntry entry;
- products.insert(entry);
- }
-
- for( zypp::MediaProductSet::const_iterator it = products.begin();
- it != products.end() ; ++it )
- {
- try
- {
- y2milestone("Using product %s in directory %s", it->_name.c_str(), it->_dir.c_str());
- id = createManagedSource(url, it->_dir, false, "", it->_name);
- ids->add( YCPInteger(id) );
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("SourceScan for '%s' product '%s' has failed"
- , url.asString().c_str(), pn.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- }
- }
- } else {
- y2debug("Creating source...");
-
- try
- {
- id = createManagedSource(url, pn, false, "", "");
- ids->add( YCPInteger(id) );
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("SourceScan for '%s' product '%s' has failed"
- , url.asString().c_str(), pn.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- }
- }
-
- y2milestone("Found sources: %s", ids->toString().c_str() );
-
- return ids;
-}
-
-/****************************************************************************************
- * @builtin SourceCreate
- *
- * @short Create a Source
- * @description
- * Load and enable all InstSrces found at media_url, i.e. all sources mentioned in /media.1/products.
- * If no /media.1/products is available, InstSrc is expected to be located directly below
- * media_url (product_dir: /).
- *
- * If a product_dir is provided, only the InstSrc located at media_url/product_dir is loaded
- * and enabled.
- *
- * @param string url The media to scan.
- * @optarg string product_dir Restrict scan to a certain InstSrc located in media_url/product_dir.
- *
- * @return integer The source_id of the first InstSrc found on the media.
- **/
-YCPValue
-PkgModuleFunctions::SourceCreate (const YCPString& media, const YCPString& pd)
-{
- // not base product, autoprobe source type
- return SourceCreateEx (media, pd, false, YCPString(""));
-}
-
-YCPValue
-PkgModuleFunctions::SourceCreateBase (const YCPString& media, const YCPString& pd)
-{
- // base product, autoprobe source type
- return SourceCreateEx (media, pd, true, YCPString(""));
-}
-
-/**
- * @builtin SourceCreateType
- * @short Create source of required type
- * @description
- * Create a source without autoprobing the source type. This builtin should be used only for "Plaindir" sources, because Plaindir sources are not automatically probed in SourceCreate() builtin.
- * @param media URL of the source
- * @param pd product directory (if empty the products will be searched)
- * @param type type of the source ("YaST", "YUM" or "Plaindir")
-*/
-
-YCPValue
-PkgModuleFunctions::SourceCreateType (const YCPString& media, const YCPString& pd, const YCPString& type)
-{
- // not base product, autoprobe source type
- return SourceCreateEx (media, pd, false, type);
-}
-
-YCPValue
-PkgModuleFunctions::SourceCreateEx (const YCPString& media, const YCPString& pd, bool base, const YCPString& source_type)
-{
- y2debug("Creating source...");
-
- zypp::Pathname pn(pd->value ());
-
- zypp::Url url;
-
- try {
- url = zypp::Url(media->value ());
- }
- catch(const zypp::Exception & expt )
- {
- y2error ("Invalid URL: %s", expt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(expt));
- return YCPInteger (-1LL);
- }
-
-
- YCPList ids;
- std::vector<zypp::RepoInfo>::size_type ret = -1;
-
- const std::string type = source_type->value();
-
- if ( pd->value().empty() ) {
- // scan all sources
- zypp::MediaProductSet products;
-
- try {
- ScanProductsWithCallBacks(url);
- products = available_products;
- }
- catch ( const zypp::Exception& excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error( "Cannot read the product list from the media" );
- return YCPInteger(-1LL);
- }
-
- if( products.empty() )
- {
- // no products found, use the base URL instead
- zypp::MediaProductEntry entry ;
- products.insert( entry );
- }
-
- for( zypp::MediaProductSet::const_iterator it = products.begin();
- it != products.end() ; ++it )
- {
- try
- {
- std::vector<zypp::RepoInfo>::size_type id = createManagedSource(url, it->_dir, base, type, it->_name);
- YRepo_Ptr repo = logFindRepository(id);
-
- LoadResolvablesFrom(repo->repoInfo());
-
- // return the id of the first product
- if ( it == products.begin() )
- ret = id;
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("SourceCreate for '%s' product '%s' has failed"
- , url.asString().c_str(), pn.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- return YCPInteger(-1LL);
- }
- }
- } else {
- y2debug("Creating source...");
-
- try
- {
- ret = createManagedSource(url, pn, base, type, "");
-
- YRepo_Ptr repo = logFindRepository(ret);
- repo->repoInfo().setEnabled(true);
-
- LoadResolvablesFrom(repo->repoInfo());
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("SourceCreate for '%s' product '%s' has failed"
- , url.asString().c_str(), pn.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- }
- }
-
- PkgFreshen();
- return YCPInteger(repos.size() - 1);
-}
-
-
-/****************************************************************************************
- * @builtin SourceSetEnabled
- *
- * @short Set the default activation state of an InsrSrc.
- * @param integer SrcId Specifies the InstSrc.
- * @param boolean enabled Default activation state of source.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceSetEnabled (const YCPInteger& id, const YCPBoolean& e)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- // no change required
- bool enable = e->value();
- if ((enable && repo->repoInfo().enabled())
- || (!enable && !repo->repoInfo().enabled()))
- return YCPBoolean(true);
-
- bool success = true;
-
- try
- {
- repo->repoInfo().setEnabled(enable);
-
- // add/remove resolvables
- if (enable)
- {
- // load resolvables only when they are missing
- if (!AnyResolvableFrom(repo->repoInfo().alias()))
- {
- success = LoadResolvablesFrom(repo->repoInfo());
- }
- }
- else
- {
- // the source has been disabled, remove resolvables from the pool
- RemoveResolvablesFrom(repo->repoInfo().alias());
- }
-
- PkgFreshen();
- }
- catch (const zypp::Exception& excpt)
- {
- std::string alias = repo->repoInfo().alias();
- y2error ("Error for '%s': %s", alias.c_str(), excpt.asString().c_str());
- _last_error.setLastError(alias + ": " + ExceptionAsString(excpt));
- success = false;
- }
-
- return YCPBoolean(success);
-}
-
-/****************************************************************************************
- * @builtin SourceSetAutorefresh
- *
- * @short Set whether this source should automaticaly refresh it's
- * meta data when it gets enabled. (default true, if not CD/DVD)
- * @param integer SrcId Specifies the InstSrc.
- * @param boolean enabled Whether autorefresh should be turned on or off.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceSetAutorefresh (const YCPInteger& id, const YCPBoolean& e)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- repo->repoInfo().setAutorefresh(e->value());
-
- return YCPBoolean( true );
-}
-
-/****************************************************************************************
- * @builtin SourceFinish
- * @short Disable an Installation Source
- * @param integer SrcId Specifies the InstSrc.
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceFinish (const YCPInteger& id)
-{
- return SourceSetEnabled(id, false);
-}
-
-/****************************************************************************************
- * @builtin SourceRefreshNow
- * @short Attempt to immediately refresh a Source
- * @description
- * The InsrSrc will be encouraged to check and refresh all metadata
- * cached on disk.
- *
- * @param integer SrcId Specifies the InstSrc.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceRefreshNow (const YCPInteger& id)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- try
- {
- zypp::RepoManager repomanager = CreateRepoManager();
- y2milestone("Refreshing metadata '%s'", repo->repoInfo().alias().c_str());
- RefreshWithCallbacks(repo->repoInfo());
-
- y2milestone("Caching source '%s'...", repo->repoInfo().alias().c_str());
- repomanager.buildCache(repo->repoInfo());
- }
- catch ( const zypp::Exception & expt )
- {
- y2error ("Error while refreshing the source: %s", expt.asString().c_str());
- _last_error.setLastError(repo->repoInfo().alias() + ": " + ExceptionAsString(expt));
- return YCPBoolean(false);
- }
-
- return YCPBoolean( true );
-}
-
-/****************************************************************************************
- * @builtin SourceDelete
- * @short Delete a Source
- * @description
- * Delete an InsrSrc. The InsrSrc together with all metadata cached on disk
- * is removed. The SrcId passed becomes invalid (other SrcIds stay valid).
- *
- * @param integer SrcId Specifies the InstSrc.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceDelete (const YCPInteger& id)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- bool success = true;
-
- try
- {
- // the resolvables cannot be used anymore, remove them
- RemoveResolvablesFrom(repo->repoInfo().alias());
-
- // update 'repos'
- repo->setDeleted();
-
- PkgFreshen();
- }
- catch (const zypp::Exception& excpt)
- {
- std::string alias = repo->repoInfo().alias();
- y2error ("Error for '%s': %s", alias.c_str(), excpt.asString().c_str());
- _last_error.setLastError(alias + ": " + ExceptionAsString(excpt));
- success = false;
- }
-
- return YCPBoolean(success);
-}
-
-/****************************************************************************************
- * @builtin SourceEditGet
- *
- * @short Get state of Sources
- * @description
- * Return a list of states for all known InstSources sorted according to the
- * source priority (highest first). A source state is a map:
- * $[
- * "SrcId" : YCPInteger,
- * "enabled" : YCPBoolean
- * "autorefresh": YCPBoolean
- * ];
- *
- * @return list<map> list of source states (map)
- **/
-YCPValue
-PkgModuleFunctions::SourceEditGet ()
-{
- YCPList ret;
-
- unsigned long index = 0;
- for( std::vector<YRepo_Ptr>::const_iterator it = repos.begin(); it != repos.end(); ++it, ++index)
- {
- if (!(*it)->isDeleted())
- {
- YCPMap src_map;
-
- src_map->add(YCPString("SrcId"), YCPInteger(index));
- // Note: enabled() is tribool
- src_map->add(YCPString("enabled"), YCPBoolean((*it)->repoInfo().enabled()));
- // Note: autorefresh() is tribool
- src_map->add(YCPString("autorefresh"), YCPBoolean((*it)->repoInfo().autorefresh()));
- src_map->add(YCPString("name"), YCPString((*it)->repoInfo().name()));
-
- ret->add(src_map);
- }
- }
-
- return ret;
-}
-
-/****************************************************************************************
- * @builtin SourceEditSet
- *
- * @short Configure properties of installation sources
- * @description
- * Set states of installation sources. Note: Enabling/disabling a source does not
- * (un)load the packages from the source! Use SourceSetEnabled() if you need to refresh
- * the packages in the pool.
- *
- * @param list source_states List of source states. Same format as returned by
- * @see SourceEditGet.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceEditSet (const YCPList& states)
-{
- bool error = false;
-
- for (int index = 0; index < states->size(); index++ )
- {
- if( ! states->value(index)->isMap() )
- {
- ycperror( "Pkg::SourceEditSet, entry not a map at index %d", index);
- error = true;
- continue;
- }
-
- YCPMap descr = states->value(index)->asMap();
-
- if (descr->value( YCPString("SrcId") ).isNull() || !descr->value(YCPString("SrcId"))->isInteger())
- {
- ycperror( "Pkg::SourceEditSet, SrcId not defined for a source description at index %d", index);
- error = true;
- continue;
- }
-
- std::vector<YRepo_Ptr>::size_type id = descr->value( YCPString("SrcId") )->asInteger()->value();
-
- YRepo_Ptr repo = logFindRepository(id);
- if (!repo)
- {
- ycperror( "Pkg::SourceEditSet, source %d not found", index);
- error = true;
- continue;
- }
-
- // now, we have the source
- if( ! descr->value( YCPString("enabled")).isNull() && descr->value(YCPString("enabled"))->isBoolean ())
- {
- bool enable = descr->value(YCPString("enabled"))->asBoolean ()->value();
-
- if (repo->repoInfo().enabled() != enable)
- {
- ycpwarning("Pkg::SourceEditSet() does not refresh the pool (src: %zd, state: %s)", id, enable ? "disabled -> enabled" : "enabled -> disabled");
- }
-
- y2debug("set enabled: %d", enable);
- repo->repoInfo().setEnabled(enable);
- }
-
- if( !descr->value(YCPString("autorefresh")).isNull() && descr->value(YCPString("autorefresh"))->isBoolean ())
- {
- bool autorefresh = descr->value(YCPString("autorefresh"))->asBoolean()->value();
- y2debug("set autorefresh: %d", autorefresh);
- repo->repoInfo().setAutorefresh( autorefresh );
- }
-
- if( !descr->value(YCPString("name")).isNull() && descr->value(YCPString("name"))->isString())
- {
- // rename the source
- y2debug("set name: %s", descr->value(YCPString("name"))->asString()->value().c_str());
- repo->repoInfo().setName(descr->value(YCPString("name"))->asString()->value());
- }
-
-#warning SourceEditSet ordering not implemented yet
- }
-
- PkgFreshen();
- return YCPBoolean( !error );
-}
-
-/////////////////////////////////////////////////////////////////////////////////////////
-//
-// DEPRECATED
-//
-/////////////////////////////////////////////////////////////////////////////////////////
-
-/****************************************************************************************
- * Pkg::SourceRaisePriority (integer SrcId) -> bool
- *
- * Raise priority of source.
- *
- * @param SrcId Specifies the InstSrc.
- *
- * @return bool
- **/
-YCPValue
-PkgModuleFunctions::SourceRaisePriority (const YCPInteger& id)
-{
-#warning SourceRaisePriority is not implemented
- y2warning("SourceRaisePriority is NOT implemented");
-/* zypp::Source_Ref src;
-
- try {
- src = logFindRepository(id->value());
- }
- catch (const zypp::Exception& excpt)
- {
- return YCPBoolean(false);
- }
-
- // raise priority by one
- src.setPriority(src.priority() + 1);
-*/
-
- return YCPBoolean( true );
-
-}
-
-/****************************************************************************************
- * Pkg::SourceLowerPriority (integer SrcId) -> void
- *
- * Lower priority of source.
- *
- * @param SrcId Specifies the InstSrc.
- *
- * @return bool
- */
-YCPValue
-PkgModuleFunctions::SourceLowerPriority (const YCPInteger& id)
-{
-#warning SourceLowerPriority is not implemented
- y2warning("SourceLowerPriority is NOT implemented");
-/*
- zypp::Source_Ref src;
-
- try {
- src = logFindRepository(id->value());
- }
- catch (const zypp::Exception& excpt)
- {
- return YCPBoolean(false);
- }
-
- // lower priority by one
- src.setPriority(src.priority() - 1);
-*/
return YCPBoolean( true );
}
-/****************************************************************************************
- * Pkg::SourceSaveRanks () -> boolean
- *
- * @short Obsoleted function, do not use
- * @return boolean true
- **/
-YCPValue
-PkgModuleFunctions::SourceSaveRanks ()
-{
- y2error( "SourceSaveRanks not implemented" );
-
- return YCPBoolean( true );
-}
-
-/****************************************************************************************
- * @builtin SourceMoveDownloadArea
- *
- * @short Move download area of CURL-based sources to specified directory
- * @param path specifies the path to move the download area to
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceMoveDownloadArea (const YCPString & path)
-{
- try
- {
- y2milestone("Moving download area of all sources to %s", path->value().c_str());
- zypp::media::MediaManager manager;
- manager.setAttachPrefix(path->value());
- }
- catch (zypp::Exception & excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error("Pkg::SourceMoveDownloadArea has failed: %s", excpt.msg().c_str());
- return YCPBoolean(false);
- }
-
- y2milestone( "Download areas moved");
-
- return YCPBoolean(true);
-}
-
-/*
- * A helper function - remove all resolvables from the repository from the pool
- */
-void PkgModuleFunctions::RemoveResolvablesFrom(const std::string &alias)
-{
- // remove the resolvables if they have been loaded
- // FIXME: can be implemented better? we need a ResStore object for removing,
- // which means search for a resolvable in the pool and get the Repository
- // object which can be asked for all resolvables in it
- for (zypp::ResPool::const_iterator it = zypp_ptr()->pool().begin()
- ; it != zypp_ptr()->pool().end()
- ; ++it)
- {
- if (it->resolvable()->repository().info().alias() == alias)
- {
- y2milestone("Removing all resolvables from '%s' from the pool...", alias.c_str());
- zypp_ptr()->removeResolvables(it->resolvable()->repository().resolvables());
- break;
- }
- }
-}
-
-/*
- * A helper function - is there any resolvable from the repository in the pool?
- */
-bool PkgModuleFunctions::AnyResolvableFrom(const std::string &alias)
-{
- for (zypp::ResPool::const_iterator it = zypp_ptr()->pool().begin()
- ; it != zypp_ptr()->pool().end()
- ; ++it)
- {
- if (it->resolvable()->repository().info().alias() == alias)
- {
- return true;
- }
- }
-
- return false;
-}
-
-/*
- * A helper function - load resolvable from the repository into the pool
- * Warning: Use AnyResolvableFrom() method for checing if the resolvables might be already loaded
- */
-bool PkgModuleFunctions::LoadResolvablesFrom(const zypp::RepoInfo &repoinfo)
-{
- bool success = true;
- unsigned int size_start = zypp_ptr()->pool().size();
- y2milestone("Loading resolvables from '%s', pool size at start: %d", repoinfo.alias().c_str(), size_start);
-
- try
- {
- zypp::RepoManager repomanager = CreateRepoManager();
-
- // build cache if needed
- if (!repomanager.isCached(repoinfo))
- {
- zypp::RepoStatus raw_metadata_status = repomanager.metadataStatus(repoinfo);
- if (raw_metadata_status.empty())
- {
- y2milestone("Missing metadata for source '%s', downloading...", repoinfo.alias().c_str());
- RefreshWithCallbacks(repoinfo);
- }
-
- y2milestone("Caching source '%s'...", repoinfo.alias().c_str());
- repomanager.buildCache(repoinfo);
- }
-
- zypp::Repository repository = repomanager.createFromCache(repoinfo);
- const zypp::ResStore &store = repository.resolvables();
-
- // load resolvables
- zypp_ptr()->addResolvables(store);
-
- y2milestone("Loaded %zd resolvables", store.size());
- }
- catch(const zypp::repo::RepoNotCachedException &excpt )
- {
- std::string alias = repoinfo.alias();
- y2error ("Resolvables from '%s' havn't been loaded: %s", alias.c_str(), excpt.asString().c_str());
- _last_error.setLastError("'" + alias + "': " + ExceptionAsString(excpt));
- success = false;
-
- // FIXME ??
- /*
- // disable the source
- y2error("Disabling source %s", url.c_str());
- repo->disable();
- */
- }
- catch (const zypp::Exception& excpt)
- {
- std::string alias = repoinfo.alias();
- y2internal("Error: Loading resolvables failed: %s", ExceptionAsString(excpt).c_str());
- _last_error.setLastError("'" + alias + "': " + ExceptionAsString(excpt));
- success = false;
- }
-
- unsigned int size_end = zypp_ptr()->pool().size();
- y2milestone("Pool size at end: %d (loaded %d resolvables)", size_end, size_end - size_start);
- return success;
-}
-
-/****************************************************************************************
- * @builtin RepositoryProbe
- *
- * @short Probe type of the repository
- * @param url specifies the path to the repository
- * @param prod_dir product directory (if empty the url is probed directly)
- * @return string repository type ("NONE" if type could be determined, nil if an error occurred (e.g. resolving the hostname)
- **/
-YCPValue PkgModuleFunctions::RepositoryProbe(const YCPString& url, const YCPString& prod_dir)
-{
- y2milestone("Probing repository type: '%s'...", url->value().c_str());
- zypp::RepoManager repomanager = CreateRepoManager();
- std::string ret;
-
- try
- {
- zypp::Url probe_url(url->value());
-
- // add the product directory
- std::string prod = prod_dir->value();
-
- if (!prod.empty())
- {
- // add "/" at the begining if it's missing
- if (std::string(prod, 0, 1) != "/")
- {
- prod = "/" + prod;
- }
-
- // merge the URL path and the product path
- std::string path = probe_url.getPathName();
- path += prod;
-
- y2milestone("Using probing path: %s", path.c_str());
- probe_url.setPathName(path);
- }
-
- // add "ro" mount option
- probe_url = addRO(probe_url);
-
- // autoprobe type of the repository
- zypp::repo::RepoType repotype = ProbeWithCallbacks(probe_url);
-
- ret = zypp2yastType(repotype.asString());
- y2milestone("Detected type: '%s'...", ret.c_str());
- }
- catch (const zypp::Exception& excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error( "Cannot detect the repository type" );
- return YCPVoid();
- }
-
- return YCPString(ret);
-}
-
-/****************************************************************************************
- * @builtin RepositoryScan
- *
- * @short Scan available products in the repository
- * @param url specifies the path to the repository
- * @return list<list<string>> list of the products: [ [ <product_name_1> <directory_1> ], ...]
- **/
-YCPValue PkgModuleFunctions::RepositoryScan(const YCPString& url)
-{
- zypp::MediaProductSet products;
-
- try
- {
- zypp::Url baseurl(url->value());
-
- baseurl = addRO(baseurl);
-
- ScanProductsWithCallBacks(baseurl);
- products = available_products;
- }
- catch ( const zypp::Exception& excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error( "Cannot read the product list from the media" );
- return YCPList();
- }
-
- YCPList ret;
-
- for( zypp::MediaProductSet::const_iterator it = products.begin();
- it != products.end() ; ++it )
- {
- YCPList prod;
-
- // add product directory
- prod.add(YCPString(it->_name));
- // add product name
- prod.add(YCPString(it->_dir.asString()));
-
- ret.add(prod);
- }
-
- y2milestone("Found products: %s", ret->toString().c_str());
-
- return ret;
-}
-
-// convert libzypp type to yast strings ("YaST", "YUM" or "Plaindir")
-std::string PkgModuleFunctions::zypp2yastType(const std::string &type)
-{
- std::string ret(type);
-
- if (type_conversion_table.empty())
- {
- // initialize the conversion map
- type_conversion_table["rpm-md"] = "YUM";
- type_conversion_table["yast2"] = "YaST";
- type_conversion_table["plaindir"] = "Plaindir";
- type_conversion_table["NONE"] = "NONE";
- }
-
- std::map<std::string,std::string>::const_iterator it = type_conversion_table.find(type);
-
- // found in the conversion table
- if (it != type_conversion_table.end())
- {
- ret = it->second;
- }
- else
- {
- y2error("Cannot convert type '%s'", type.c_str());
- }
-
- return ret;
-}
-
-std::string PkgModuleFunctions::yast2zyppType(const std::string &type)
-{
- // do conversion from the Yast type ("YaST", "YUM", "Plaindir")
- // to libzypp type ("yast", "yum", "plaindir")
- // we can simply use toLower instead of a conversion table
- // in this case
- return zypp::str::toLower(type);
-}
-
Copied: trunk/pkg-bindings/src/Source_Get.cc (from r42708, trunk/pkg-bindings/src/Source.cc)
URL: http://svn.opensuse.org/viewcvs/yast/trunk/pkg-bindings/src/Source_Get.cc?p…
==============================================================================
--- trunk/pkg-bindings/src/Source.cc (original)
+++ trunk/pkg-bindings/src/Source_Get.cc Thu Dec 6 07:56:58 2007
@@ -1,2940 +1,363 @@
-/*---------------------------------------------------------------------\
-| |
-| __ __ ____ _____ ____ |
-| \ \ / /_ _/ ___|_ _|___ \ |
-| \ V / _` \___ \ | | __) | |
-| | | (_| |___) || | / __/ |
-| |_|\__,_|____/ |_| |_____| |
-| |
-| core system |
-| (C) SuSE GmbH |
-\----------------------------------------------------------------------/
-
- File: PkgModuleFunctionsSource.cc
-
- Author: Klaus Kaempf <kkaempf(a)suse.de>
- Maintainer: Klaus Kaempf <kkaempf(a)suse.de>
-
- Summary: Access to Installation Sources
- Namespace: Pkg
- Purpose: Access to InstSrc
- Handles source related Pkg::function (list_of_arguments) calls
- from WFMInterpreter.
-/-*/
-//#include <unistd.h>
-//#include <sys/statvfs.h>
-
-#include <iostream>
-
-#include <ycpTools.h>
-#include <PkgModule.h>
-#include <PkgModuleFunctions.h>
-
-#include <Callbacks.h>
-#include <Callbacks.YCP.h>
-
-#include <zypp/Product.h>
-#include <zypp/media/MediaManager.h>
-#include <zypp/media/Mount.h>
-#include <zypp/Pathname.h>
-
-#include <zypp/RepoInfo.h>
-#include <zypp/RepoManager.h>
-#include <zypp/Fetcher.h>
-#include <zypp/repo/RepoType.h>
-#include <zypp/MediaProducts.h>
-#include <zypp/ExternalProgram.h>
-#include <zypp/ProgressData.h>
-
-#include <sstream> // ostringstream
-
-#include <PkgProgress.h>
-
-/*
- Textdomain "pkg-bindings"
-*/
-
-// scanned available products
-// hack: zypp/MediaProducts.h cannot be included in PkgModuleFunctions.h
-zypp::MediaProductSet available_products;
-
-// this method should be used instead of zypp::productsInMedia()
-// it initializes the download callbacks
-void PkgModuleFunctions::ScanProductsWithCallBacks(const zypp::Url &url)
-{
- CallInitDownload(std::string(_("Scanning products in ") + url.asString()));
-
- extern ZyppRecipients::MediaChangeSensitivity _silent_probing;
- // remember the current value
- ZyppRecipients::MediaChangeSensitivity _silent_probing_old = _silent_probing;
-
- // disable media change callback for optional file
- _silent_probing = ZyppRecipients::MEDIA_CHANGE_DISABLE;
-
- y2milestone("Scanning products in %s ...", url.asString().c_str());
-
- try
- {
- available_products.clear();
- zypp::productsInMedia(url, available_products);
- }
- catch(...)
- {
- // call the final event even in case of exception
- CallDestDownload();
-
- // restore the probing flag
- _silent_probing = _silent_probing_old;
-
- // rethrow the execption
- throw;
- }
-
- CallDestDownload();
-
- // restore the probing flag
- _silent_probing = _silent_probing_old;
-}
-
-void PkgModuleFunctions::CallSourceReportStart(const std::string &text)
-{
- // get the YCP callback handler
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_SourceReportStart);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- // add parameters
- ycp_handler->appendParameter( YCPInteger(0LL) );
- ycp_handler->appendParameter( YCPString("") );
- ycp_handler->appendParameter( YCPString(text) );
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-
-void PkgModuleFunctions::CallSourceReportEnd(const std::string &text)
-{
- // get the YCP callback handler for end event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_SourceReportEnd);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- // add parameters
- ycp_handler->appendParameter( YCPInteger(0LL) );
- ycp_handler->appendParameter( YCPString("") );
- ycp_handler->appendParameter( YCPString(text) );
- ycp_handler->appendParameter( YCPString("NO_ERROR") );
- ycp_handler->appendParameter( YCPString("") );
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-
-void PkgModuleFunctions::CallSourceReportInit()
-{
- // get the YCP callback handler for init event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_SourceReportInit);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-
-void PkgModuleFunctions::CallSourceReportDestroy()
-{
- // get the YCP callback handler for destroy event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_SourceReportDestroy);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-
-void PkgModuleFunctions::CallInitDownload(const std::string &task)
-{
- // get the YCP callback handler for destroy event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_InitDownload);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- ycp_handler->appendParameter(YCPString(task));
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-
-void PkgModuleFunctions::CallDestDownload()
-{
- // get the YCP callback handler for destroy event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_DestDownload);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-
-// this method should be used instead of RepoManager::refreshMetadata()
-void PkgModuleFunctions::RefreshWithCallbacks(const zypp::RepoInfo &repo)
-{
- CallInitDownload(std::string(_("Refreshing repository ") + repo.alias()));
-
- try
- {
- zypp::RepoManager repomanager = CreateRepoManager();
- repomanager.refreshMetadata(repo);
- }
- catch(...)
- {
- // call the final event even in case of exception
- CallDestDownload();
- // rethrow the execption
- throw;
- }
-
- CallDestDownload();
-}
-
-// this method should be used instead of RepoManager::probe()
-zypp::repo::RepoType PkgModuleFunctions::ProbeWithCallbacks(const zypp::Url &url)
-{
- CallInitDownload(std::string(_("Probing repository ") + url.asString()));
-
- zypp::repo::RepoType repotype;
-
- extern ZyppRecipients::MediaChangeSensitivity _silent_probing;
- // remember the current value
- ZyppRecipients::MediaChangeSensitivity _silent_probing_old = _silent_probing;
-
- // disable media change callback for optional file
- _silent_probing = ZyppRecipients::MEDIA_CHANGE_DISABLE;
-
- try
- {
- // probe type of the repository
- zypp::RepoManager repomanager = CreateRepoManager();
- repotype = repomanager.probe(url);
- }
- catch(...)
- {
- // call the final event even in case of exception
- CallDestDownload();
-
- // restore the probing flag
- _silent_probing = _silent_probing_old;
-
- // rethrow the execption
- throw;
- }
-
- CallDestDownload();
-
- // restore the probing flag
- _silent_probing = _silent_probing_old;
-
- return repotype;
-}
-
-/**
- * Logging helper:
- * call zypp::SourceManager::sourceManager()->findSource
- * and in case of exception, log error and setLastError AND RETHROW
- */
-YRepo_Ptr PkgModuleFunctions::logFindRepository(std::vector<YRepo_Ptr>::size_type id)
-{
- try
- {
- if (id < 0 || id >= repos.size())
- {
- // not found
- throw(std::exception());
- }
-
- if (!repos[id])
- {
- // not found
- throw(std::exception());
- }
-
- if (repos[id]->isDeleted())
- {
- y2error("Source %zd has been deleted, the ID is not valid", id);
- return YRepo_Ptr();
- }
-
- return repos[id];
- }
- catch (...)
- {
- y2error("Cannot find source with ID: %zd", id);
- // TODO: improve the error message
- _last_error.setLastError(_("Cannot find source"));
- }
-
- // not found, return empty pointer
- return YRepo_Ptr();
-}
-
-long long PkgModuleFunctions::logFindAlias(const std::string &alias) const
-{
- std::vector<YRepo_Ptr>::size_type index = 0;
-
- for(std::vector<YRepo_Ptr>::const_iterator it = repos.begin(); it != repos.end() ; ++it, ++index)
- {
- if (!(*it)->isDeleted() && (*it)->repoInfo().alias() == alias)
- return index;
- }
-
- return -1LL;
-}
-
-bool PkgModuleFunctions::aliasExists(const std::string &alias) const
-{
- for(std::vector<YRepo_Ptr>::const_iterator it = repos.begin(); it != repos.end() ; ++it)
- {
- if (!(*it)->isDeleted() && (*it)->repoInfo().alias() == alias)
- return true;
- }
-
- return false;
-}
-
-/****************************************************************************************
- * @builtin SourceSetRamCache
- * @short Obsoleted function, do not use
- * @param boolean
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceSetRamCache (const YCPBoolean& a)
-{
- y2warning( "Pkg::SourceSetRamCache is obsolete and does nothing");
- return YCPBoolean( true );
-}
-
-
-/****************************************************************************************
- * @builtin SourceRestore
- *
- * @short Restore the sources from the persistent store
- * @description
- * Make sure the Source Manager is up and knows all available installation sources.
- * It's safe to call this multiple times, and once the installation sources are
- * actually enabled, it's even cheap
- *
- * @return boolean True on success
- **/
-YCPValue
-PkgModuleFunctions::SourceRestore()
-{
- if (repos.size() > 0)
- {
- y2warning("Number of registered repositories: %zd, skipping repository load!", repos.size());
- return YCPBoolean(true);
- }
-
- bool success = true;
-
- try
- {
- zypp::RepoManager repomanager = CreateRepoManager();
- std::list<zypp::RepoInfo> reps = repomanager.knownRepositories();
-
- repos.clear();
- for (std::list<zypp::RepoInfo>::iterator it = reps.begin();
- it != reps.end(); ++it)
- {
- repos.push_back(new YRepo(*it));
- }
- }
- catch (const zypp::Exception& excpt)
- {
- // FIXME: assuming the sources are already initialized
- y2error ("Error in SourceRestore: %s", excpt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- success = false;
- }
-
- return YCPBoolean(success);
-}
-
-/****************************************************************************************
- * @builtin SourceGetBrokenSources
- *
- * @short Return list of broken sources (sources which failed to restore)
- * @description
- * Get list of all sources which could not have been restored.
- * @return list<string> list of aliases (product names or URLs)
- **/
-YCPValue PkgModuleFunctions::SourceGetBrokenSources()
-{
- y2warning("Pkg::SourceGetBrokenSources() is obsoleted, it's not needed anymore.");
- return YCPList();
-}
-
-bool PkgModuleFunctions::SourceLoadReceiver(const zypp::ProgressData &progress)
-{
- y2milestone("Source Load receiver: %lld (%lld%%)", progress.val(), progress.reportValue());
-
- // get the YCP callback handler for destroy event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_ProcessProgress);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- ycp_handler->appendParameter(YCPInteger(progress.reportValue()));
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-
- return true;
-}
-
-/****************************************************************************************
- * @builtin SourceLoad
- *
- * @short Load resolvables from the installation sources
- * @description
- * Refresh the pool - Add/remove resolvables from the enabled/disabled sources.
- * @return boolean True on success
- **/
-YCPValue
-PkgModuleFunctions::SourceLoad()
-{
- std::list<std::string> stages;
- stages.push_back("Refresh Sources");
- stages.push_back("Rebuild Cache");
- stages.push_back("Load Data");
-
- PkgProgress pkgprogress(_callbackHandler);
-
- // 3 steps per repository (download, cache rebuild, load resolvables)
- pkgprogress.Start("Loading the Package Manager...", stages, "help");
-
- YCPValue ret = SourceLoadImpl(pkgprogress);
-
- pkgprogress.Done();
-
- return ret;
-}
-
-
-/****************************************************************************************
- * @builtin SourceLoad
- *
- * @short Load resolvables from the installation sources
- * @description
- * Refresh the pool - Add/remove resolvables from the enabled/disabled sources.
- * @return boolean True on success
- **/
-YCPValue
-PkgModuleFunctions::SourceLoadImpl(PkgProgress &progress)
-{
- bool success = true;
-
- int repos_to_load = 0;
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
- {
- repos_to_load++;
- }
- }
-
- // set max. value (3 steps per repository - refresh, rebuild, load)
- zypp::ProgressData prog_total(repos_to_load * 3);
- prog_total.sendTo(progress.Receiver());
-
- zypp::RepoManager repomanager = CreateRepoManager();
-
- // refresh metadata
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- // load resolvables only from enabled repos which are not deleted
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
- {
- // sub tasks
- zypp::CombinedProgressData refresh_subprogress(prog_total, 1);
-
- if (AnyResolvableFrom((*it)->repoInfo().alias()))
- {
- y2milestone("Resolvables from '%s' are already present, not loading", (*it)->repoInfo().alias().c_str());
- }
- else
- {
- // autorefresh the source
- if ((*it)->repoInfo().autorefresh())
- {
- try
- {
- y2milestone("Autorefreshing source: %s", (*it)->repoInfo().alias().c_str());
- RefreshWithCallbacks((*it)->repoInfo());
-
- zypp::ProgressData prog(1);
- prog.sendTo(refresh_subprogress);
- RefreshWithCallbacks((*it)->repoInfo());
- prog.toMax();
- }
- // NOTE: subtask progresses are reported as done in the descructor
- // no need to handle them in the exception code
- catch (const zypp::Exception& excpt)
- {
- y2error ("Error in SourceLoad: %s", excpt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- success = false;
- }
- }
- }
- }
- }
-
- progress.NextStage();
-
- // rebuild cache
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- // load resolvables only from enabled repos which are not deleted
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
- {
- // sub tasks
- zypp::CombinedProgressData rebuild_subprogress(prog_total, 1);
-
- if (AnyResolvableFrom((*it)->repoInfo().alias()))
- {
- y2milestone("Resolvables from '%s' are already present, not loading", (*it)->repoInfo().alias().c_str());
- }
- else
- {
- // autorefresh the source
- if ((*it)->repoInfo().autorefresh())
- {
- try
- {
- // rebuild cache (the default policy is "if needed")
- y2milestone("Rebuilding cache for '%s'...", (*it)->repoInfo().alias().c_str());
-
- zypp::ProgressData prog(1);
- prog.sendTo(rebuild_subprogress);
- repomanager.buildCache((*it)->repoInfo());
- prog.toMax();
- }
- // NOTE: subtask progresses are reported as done in the descructor
- // no need to handle them in the exception code
- catch (const zypp::Exception& excpt)
- {
- y2error ("Error in SourceLoad: %s", excpt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- success = false;
- }
- }
- }
- }
- }
-
- progress.NextStage();
-
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- // load resolvables only from enabled repos which are not deleted
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
- {
- // sub tasks
- zypp::CombinedProgressData load_subprogress(prog_total, 1);
-
- if (AnyResolvableFrom((*it)->repoInfo().alias()))
- {
- y2milestone("Resolvables from '%s' are already present, not loading", (*it)->repoInfo().alias().c_str());
- }
- else
- {
- zypp::ProgressData prog(1);
- prog.sendTo(load_subprogress);
-
- // load objects
- success = LoadResolvablesFrom((*it)->repoInfo()) && success;
-
- prog.toMax();
- }
- }
- }
-
- // report 100%
- prog_total.toMax();
-
- return YCPBoolean(success);
-}
-
-
-/****************************************************************************************
- * @builtin SourceStartManager
- *
- * @short Start the source manager - restore the sources and load the resolvables
- * @description
- * Calls SourceRestore(), if argument enable is true SourceLoad() is called.
- * @param boolean enable If true the resolvables are loaded from the enabled sources
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceStartManager (const YCPBoolean& enable)
-{
- PkgProgress pkgprogress(_callbackHandler);
-
- // display the progress only when 'enable' is true
- if (enable->value())
- {
- std::list<std::string> stages;
- stages.push_back("Load Sources");
- stages.push_back("Refresh Sources");
- stages.push_back("Rebuild Cache");
- stages.push_back("Load Data");
-
- // 3 steps per repository (download, cache rebuild, load resolvables)
- pkgprogress.Start("Loading the Package Manager...", stages, "help");
- }
-
- YCPValue ret = SourceStartManagerImpl(enable, pkgprogress);
-
- if (enable->value())
- {
- pkgprogress.Done();
- }
-
- return ret;
-}
-
-/****************************************************************************************
- * @builtin SourceStartManager
- *
- * @short Start the source manager - restore the sources and load the resolvables
- * @description
- * Calls SourceRestore(), if argument enable is true SourceLoad() is called.
- * @param boolean enable If true the resolvables are loaded from the enabled sources
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceStartManagerImpl(const YCPBoolean& enable, PkgProgress &progress)
-{
- YCPValue success = SourceRestore();
-
- progress.NextStage();
-
- if( enable->value() )
- {
- if (!success->asBoolean()->value())
- {
- y2warning("SourceStartManager: Some sources have not been restored, loading only the active sources...");
- }
-
- // enable all sources and load the resolvables
- success = YCPBoolean(SourceLoadImpl(progress)->asBoolean()->value() && success->asBoolean()->value());
- }
-
- return success;
-}
-
-/****************************************************************************************
- * @builtin SourceStartCache
- *
- * @short Make sure the InstSrcManager is up, and return the list of SrcIds.
- * @description
- * Make sure the InstSrcManager is up, and return the list of SrcIds.
- * In fact nothing more than:
- *
- * <code>
- * SourceStartManager( enabled_only );
- * return SourceGetCurrent( enabled_only );
- * </code>
- *
- * @param boolean enabled_only If true, make sure all InstSrces are enabled according to
- * their default, and return the Ids of enabled InstSrces only. If false, return
- * the Ids of all known InstSrces.
- *
- * @return list<integer> list of SrcIds
- **/
-YCPValue
-PkgModuleFunctions::SourceStartCache (const YCPBoolean& enabled)
-{
- try
- {
- SourceStartManager(enabled);
-
- return SourceGetCurrent(enabled);
- }
- catch (const zypp::Exception& excpt)
- {
- y2error ("Error in SourceStartCache: %s", excpt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- }
- // catch an exception from boost (e.g. a file cannot be read by non-root user)
- catch (const std::exception& err)
- {
- y2error ("Error in SourceStartCache: %s", err.what());
- _last_error.setLastError(err.what());
- }
- catch (...)
- {
- y2error("Unknown error in SourceStartCache");
- }
-
- return YCPList();
-}
-
-/****************************************************************************************
- * @builtin SourceCleanupBroken
- *
- * @short Clean up all sources that were not properly restored on the last
- * call of SourceStartManager or SourceStartCache.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceCleanupBroken ()
-{
- y2warning("Pkg::SourceCleanupBroken() is obsoleted, it's not needed anymore.");
- return YCPBoolean(true);
-}
-
-/****************************************************************************************
- * @builtin SourceGetCurrent
- *
- * @short Return the list of all InstSrc Ids.
- *
- * @param boolean enabled_only If true, or omitted, return the Ids of all enabled InstSrces.
- * If false, return the Ids of all known InstSrces.
- *
- * @return list<integer> list of SrcIds (integer)
- **/
-YCPValue
-PkgModuleFunctions::SourceGetCurrent (const YCPBoolean& enabled)
-{
- YCPList res;
-
- std::vector<YRepo_Ptr>::size_type index = 0;
- for( std::vector<YRepo_Ptr>::const_iterator it = repos.begin(); it != repos.end() ; ++it, ++index )
- {
- // ignore disabled sources if requested
- if (enabled->value())
- {
- // Note: enabled() is tribool!
- if ((*it)->repoInfo().enabled())
- {
- }
- else if (!(*it)->repoInfo().enabled())
- {
- continue;
- }
- else
- {
- continue;
- }
- }
-
- // ignore deleted sources
- if ((*it)->isDeleted())
- {
- continue;
- }
-
- res->add( YCPInteger(index) );
- }
-
- return res;
-}
-
-/****************************************************************************************
- * @builtin SourceReleaseAll
- *
- * @short Release all medias hold by all sources
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceReleaseAll ()
-{
- y2milestone("Releasing all sources...");
- bool ret = true;
-
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- try
- {
- (*it)->mediaAccess()->release();
- }
- catch (const zypp::media::MediaException & ex)
- {
- y2warning("Failed to release media for repo: %s", ex.msg().c_str());
- ret = false;
- }
- }
-
- return YCPBoolean(ret);
-}
-
-/******************************************************************************
- * @builtin SourceSaveAll
- *
- * @short Save all InstSrces.
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceSaveAll ()
-{
- y2milestone("Saving the source setup...");
-
- zypp::RepoManager repomanager = CreateRepoManager();
-
- // remove deleted repos (the old configurations) at first
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- // the repo has been removed
- if ((*it)->isDeleted())
- {
- std::string repo_alias = (*it)->repoInfo().alias();
-
- try
- {
- // remove the metadata
- zypp::RepoStatus raw_metadata_status = repomanager.metadataStatus((*it)->repoInfo());
- if (!raw_metadata_status.empty())
- {
- y2milestone("Removing metadata for source '%s'...", repo_alias.c_str());
- repomanager.cleanMetadata((*it)->repoInfo());
- }
-
- // remove the cache
- if (repomanager.isCached((*it)->repoInfo()))
- {
- y2milestone("Removing cache for '%s'...", repo_alias.c_str());
- repomanager.cleanCache((*it)->repoInfo());
- }
-
- repomanager.getRepositoryInfo(repo_alias);
- y2milestone("Removing repository '%s'", repo_alias.c_str());
- repomanager.removeRepository((*it)->repoInfo());
- }
- catch (const zypp::repo::RepoNotFoundException &ex)
- {
- // repository not found -- not critical, continue
- y2warning("No such repository: %s", repo_alias.c_str());
- }
- catch (const zypp::Exception & excpt)
- {
- y2error("Pkg::SourceSaveAll has failed: %s", excpt.msg().c_str() );
- _last_error.setLastError(ExceptionAsString(excpt));
- return YCPBoolean(false);
- }
- }
- }
-
- // save all repos (the current configuration)
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- if (!(*it)->isDeleted())
- {
- std::string current_alias = (*it)->repoInfo().alias();
-
- try
- {
- try
- {
- // if the repository already exists then just modify it
- repomanager.getRepositoryInfo(current_alias);
- y2milestone("Modifying repository '%s'", current_alias.c_str());
- repomanager.modifyRepository(current_alias, (*it)->repoInfo());
- }
- catch (const zypp::repo::RepoNotFoundException &ex)
- {
- // the repository was not found, add it
- y2milestone("Adding repository '%s'", current_alias.c_str());
- repomanager.addRepository((*it)->repoInfo());
- }
- }
- catch (zypp::Exception & excpt)
- {
- y2error("Pkg::SourceSaveAll has failed: %s", excpt.msg().c_str() );
- _last_error.setLastError(ExceptionAsString(excpt));
- return YCPBoolean(false);
- }
- }
- }
-
- y2milestone("All sources have been saved");
-
- return YCPBoolean(true);
-}
-
-/****************************************************************************************
- * @builtin SourceFinishAll
- *
- * @short Save and then disable all InstSrces.
- * @description
- * If there are no enabled sources, do nothing
- * (idempotence hack, broken design: #155459, #176013, use SourceSaveAll).
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceFinishAll ()
-{
- try
- {
- bool found_enabled = false;
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
- {
- found_enabled = true;
- break;
- }
- }
-
- if (!found_enabled)
- {
- y2milestone( "No enabled sources, skipping SourceFinishAll()" );
- return YCPBoolean( true );
- }
-
- SourceSaveAll();
-
- y2milestone( "Disabling all sources...") ;
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- (*it)->repoInfo().setEnabled(false);
- }
- // TODO FIXME remove all resolvables??
- }
- catch (zypp::Exception & excpt)
- {
- y2error("Pkg::SourceFinishAll has failed: %s", excpt.msg().c_str() );
- _last_error.setLastError(ExceptionAsString(excpt));
- return YCPBoolean(false);
- }
-
- y2milestone("All sources have been saved and disabled");
-
- return YCPBoolean(true);
-}
-
-/////////////////////////////////////////////////////////////////////////////////////////
-// Query individual sources
-/////////////////////////////////////////////////////////////////////////////////////////
-
-/****************************************************************************************
- * @builtin SourceGeneralData
- *
- * @short Get general data about the source
- * @description
- * Return general data about the source as a map:
- *
- * <code>
- * $[
- * "enabled" : YCPBoolean,
- * "autorefresh": YCPBoolean,
- * "product_dir": YCPString,
- * "type" : YCPString,
- * "url" : YCPString (without password, but see SourceURL),
- * "alias" : YCPString,
- * "name" : YCPString,
- * ];
- *
- * </code>
- * @param integer SrcId Specifies the InstSrc to query.
- * @return map
- **/
-YCPValue
-PkgModuleFunctions::SourceGeneralData (const YCPInteger& id)
-{
- YCPMap data;
-
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPVoid ();
-
- // convert type to the old strings ("YaST", "YUM" or "Plaindir")
- std::string srctype = zypp2yastType(repo->repoInfo().type().asString());
-
- data->add( YCPString("enabled"), YCPBoolean(repo->repoInfo().enabled()));
- data->add( YCPString("autorefresh"), YCPBoolean(repo->repoInfo().autorefresh()));
- data->add( YCPString("type"), YCPString(srctype));
- data->add( YCPString("product_dir"), YCPString(repo->repoInfo().path().asString()));
-
- // check if there is an URL
- if (repo->repoInfo().baseUrlsBegin() != repo->repoInfo().baseUrlsEnd())
- {
- data->add( YCPString("url"), YCPString(repo->repoInfo().baseUrlsBegin()->asString()));
- }
-
- data->add( YCPString("alias"), YCPString(repo->repoInfo().alias()));
- data->add( YCPString("name"), YCPString(repo->repoInfo().name()));
-
- YCPList base_urls;
- for( zypp::RepoInfo::urls_const_iterator it = repo->repoInfo().baseUrlsBegin(); it != repo->repoInfo().baseUrlsEnd(); ++it)
- {
- base_urls->add(YCPString(it->asString()));
- }
- data->add( YCPString("base_urls"), base_urls);
-
- data->add( YCPString("mirror_list"), YCPString(repo->repoInfo().mirrorListUrl().asString()));
-
- return data;
-}
-
-/******************************************************************************
- * @builtin SourceURL
- *
- * @short Get full source URL, including password
- * @param integer SrcId Specifies the InstSrc to query.
- * @return string or nil on failure
- **/
-YCPValue
-PkgModuleFunctions::SourceURL (const YCPInteger& id)
-{
-
- const YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPVoid();
-
- std::string url;
-
- if (repo->repoInfo().baseUrlsBegin() != repo->repoInfo().baseUrlsEnd())
- {
- // #186842
- url = repo->repoInfo().baseUrlsBegin()->asCompleteString();
- }
-
- return YCPString(url);
-}
-
-/****************************************************************************************
- * @builtin SourceMediaData
- * @short Return media data about the source
- * @description
- * Return media data about the source as a map:
- *
- * <code>
- * $["media_count": YCPInteger,
- * "media_id" : YCPString,
- * "media_vendor" : YCPString,
- * "url" : YCPString,
- * ];
- * </code>
- *
- * @param integer SrcId Specifies the InstSrc to query.
- * @return map
- **/
-YCPValue
-PkgModuleFunctions::SourceMediaData (const YCPInteger& id)
-{
- YCPMap data;
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPVoid ();
-
- std::string alias = repo->repoInfo().alias();
- bool found_resolvable = false;
- int max_medium = 1;
-
- for (zypp::ResPool::const_iterator it = zypp_ptr()->pool().begin()
- ; it != zypp_ptr()->pool().end()
- ; ++it)
- {
- if (it->resolvable()->repository().info().alias() == alias)
- {
- int medium = it->resolvable()->mediaNr();
-
- if (medium > max_medium)
- {
- max_medium = medium;
- }
- }
- }
-
- if (found_resolvable)
- {
- data->add( YCPString("media_count"), YCPInteger(max_medium));
- }
- else
- {
- y2error("No resolvable from repository '%s' found, cannot get number of media (use Pkg::SourceLoad() to load the resolvables)", alias.c_str());
- }
-
- y2warning("Pkg::SourceMediaData() doesn't return \"media_id\" and \"media_vendor\" values anymore.");
-
- // SourceMediaData returns URLs without password
- if (repo->repoInfo().baseUrlsBegin() != repo->repoInfo().baseUrlsEnd())
- {
- data->add( YCPString("url"), YCPString(repo->repoInfo().baseUrlsBegin()->asString()));
-
- // add all base URLs
- YCPList base_urls;
- for( zypp::RepoInfo::urls_const_iterator it = repo->repoInfo().baseUrlsBegin(); it != repo->repoInfo().baseUrlsEnd(); ++it)
- {
- base_urls->add(YCPString(it->asString()));
- }
- data->add( YCPString("base_urls"), base_urls);
- }
-
- return data;
-}
-
-/****************************************************************************************
- * @builtin SourceProductData
- * @short Return Product data about the source
- * @param integer SrcId Specifies the InstSrc to query.
- * @description
- * Product data about the source as a map:
- *
- * <code>
- * $[
- * "label" : YCPString,
- * "vendor" : YCPString,
- * "productname" : YCPString,
- * "productversion" : YCPString,
- * "relnotesurl" : YCPString,
- * ];
- * </code>
- *
- * @return map
- **/
-YCPValue
-PkgModuleFunctions::SourceProductData (const YCPInteger& src_id)
-{
- YCPMap ret;
-
- try
- {
- // find a product for the given source
- zypp::ResPool::byKind_iterator it = zypp_ptr()->pool().byKindBegin(zypp::ResTraits<zypp::Product>::kind);
-
- for( ; it != zypp_ptr()->pool().byKindEnd(zypp::ResTraits<zypp::Product>::kind) ; ++it)
- {
- zypp::Product::constPtr product = boost::dynamic_pointer_cast<const zypp::Product>( it->resolvable() );
-
- if( logFindAlias(product->repository().info().alias()) == src_id->value() )
- {
- ret->add( YCPString("label"), YCPString( product->summary() ) );
- ret->add( YCPString("vendor"), YCPString( product->vendor() ) );
- ret->add( YCPString("productname"), YCPString( product->name() ) );
- ret->add( YCPString("productversion"), YCPString( product->edition().version() ) );
- ret->add( YCPString("relnotesurl"), YCPString( product->releaseNotesUrl().asString()));
-
- #warning SourceProductData not finished
- /*
- data->add( YCPString("datadir"), YCPString( descr->content_datadir().asString() ) );
- TODO (?): "baseproductname", "baseproductversion", "defaultbase", "architectures",
- "requires", "linguas", "labelmap", "language", "timezone", "descrdir", "datadir"
- */
-
- break;
- }
- }
-
- if( it == zypp_ptr()->pool().byKindEnd(zypp::ResTraits<zypp::Product>::kind) )
- {
- y2error ("Product for source '%lld' not found", src_id->value());
- }
- }
- catch (...)
- {
- }
-
- return ret;
-}
-
-/****************************************************************************************
- * @builtin SourceProduct
- * @short Obsoleted function, do not use, see SourceProductData builtin
- * @deprecated
- * @param integer
- * @return map empty map
- **/
-YCPValue
-PkgModuleFunctions::SourceProduct (const YCPInteger& id)
-{
- /* TODO FIXME */
- y2error("Pkg::SourceProduct() is obsoleted, use Pkg::SourceProductData() instead!");
- return YCPMap();
-}
-
-
-YCPValue PkgModuleFunctions::SourceProvideFileCommon(const YCPInteger &id,
- const YCPInteger &mid,
- const YCPString& f,
- const YCPBoolean & optional)
-{
- CallInitDownload(std::string(_("Downloading ") + f->value()));
-
- bool found = true;
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- found = false;
-
- extern ZyppRecipients::MediaChangeSensitivity _silent_probing;
- // remember the current value
- ZyppRecipients::MediaChangeSensitivity _silent_probing_old = _silent_probing;
-
- // disable media change callback for optional file
- if (optional->value())
- _silent_probing = ZyppRecipients::MEDIA_CHANGE_OPTIONALFILE;
-
- zypp::filesystem::Pathname path; // FIXME use ManagedMedia
- if (found)
- {
- try
- {
- path = repo->mediaAccess()->provideFile(f->value(), mid->value());
- y2milestone("local path: '%s'", path.asString().c_str());
- }
- catch (const zypp::Exception& excpt)
- {
- found = false;
-
- if (!optional->value())
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2milestone("File not found: %s", f->value_cstr());
- }
- }
- }
-
- // set the original probing value
- _silent_probing = _silent_probing_old;
-
- CallDestDownload();
-
- if (found)
- {
- return YCPString(path.asString());
- }
- else
- {
- return YCPVoid();
- }
-}
-
-
-/****************************************************************************************
- * @builtin SourceProvideFile
- *
- * @short Make a file available at the local filesystem
- * @description
- * Let an InstSrc provide some file (make it available at the local filesystem).
- *
- * @param integer SrcId Specifies the InstSrc .
- * @param integer medianr Number of the media the file is located on ('1' for the 1st media).
- * @param string file Filename relative to the media root.
- *
- * @return string local path as string
- **/
-YCPValue
-PkgModuleFunctions::SourceProvideFile (const YCPInteger& id, const YCPInteger& mid, const YCPString& f)
-{
- return SourceProvideFileCommon(id, mid, f, false /*optional*/);
-}
-
-/****************************************************************************************
- * @builtin SourceProvideOptionalFile
- *
- * @short Make an optional file available at the local filesystem
- * @description
- * Let an InstSrc provide some file (make it available at the local filesystem).
- * If the file doesn't exist don't ask user for another medium and return nil
- *
- * @param integer SrcId Specifies the InstSrc .
- * @param integer medianr Number of the media the file is located on ('1' for the 1st media).
- * @param string file Filename relative to the media root.
- *
- * @return string local path as string
- **/
-YCPValue
-PkgModuleFunctions::SourceProvideOptionalFile (const YCPInteger& id, const YCPInteger& mid, const YCPString& f)
-{
- return SourceProvideFileCommon(id, mid, f, true /*optional*/);
-}
-
-/****************************************************************************************
- * @builtin SourceProvideDir
- * @short make a directory available at the local filesystem
- * @description
- * Let an InstSrc provide some directory (make it available at the local filesystem) and
- * all the files within it (non recursive).
- *
- * @param integer SrcId Specifies the InstSrc .
- * @param integer medianr Number of the media the file is located on ('1' for the 1st media).
- * @param string dir Directoryname relative to the media root.
- * @return string local path as string
- */
-YCPValue
-PkgModuleFunctions::SourceProvideDir (const YCPInteger& id, const YCPInteger& mid, const YCPString& d)
-{
- y2warning("Pkg::SourceProvideDir() is obsoleted use Pkg::SourceProvideDirectory() instead");
- // non optional, non recursive
- return SourceProvideDirectory(id, mid, d, false, false);
-}
-
-
-/****************************************************************************************
- * @builtin SourceProvideDirectory
- * @short make a directory available at the local filesystem
- * @description
- * Download a directory from repository (make it available at the local filesystem) and
- * all the files within it.
- *
- * @param integer id repository to use (id)
- * @param integer mid Number of the media where the directory is located on ('1' for the 1st media).
- * @param string d Directory name relative to the media root.
- * @param boolean optional set to true if the directory may not exist (do not report errors)
- * @param boolean recursive set to true to provide all subdirectories recursively
- * @return string local path as string or nil when an error occured
- */
-YCPValue
-PkgModuleFunctions::SourceProvideDirectory(const YCPInteger& id, const YCPInteger& mid, const YCPString& d, const YCPBoolean &optional, const YCPBoolean &recursive)
-{
- CallInitDownload(std::string(_("Downloading ") + d->value()));
-
- bool found = true;
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- found = false;
-
- zypp::filesystem::Pathname path; // FIXME user ManagedMedia
-
- extern ZyppRecipients::MediaChangeSensitivity _silent_probing;
- // remember the current value
- ZyppRecipients::MediaChangeSensitivity _silent_probing_old = _silent_probing;
-
- // disable media change callback for optional file
- if (optional->value())
- _silent_probing = ZyppRecipients::MEDIA_CHANGE_OPTIONALFILE;
-
- if (found)
- {
- try
- {
- path = repo->mediaAccess()->provideDir(d->value(), recursive->value(), mid->value());
- }
- catch (const zypp::Exception& excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2milestone ("Directory not found: %s", d->value_cstr());
- found = false;
- }
- }
-
- // set the original probing value
- _silent_probing = _silent_probing_old;
-
- CallDestDownload();
-
- if (found)
- {
- return YCPString(path.asString());
- }
- else
- {
- return YCPVoid();
- }
-}
-
-/****************************************************************************************
- * @builtin SourceChangeUrl
- * @short Change Source URL
- * @description
- * Change url of an InstSrc. Used primarely when re-starting during installation
- * and a cd-device changed from hdX to srX since ide-scsi was activated.
- * @param integer SrcId Specifies the InstSrc.
- * @param string url The new url to use.
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceChangeUrl (const YCPInteger& id, const YCPString& u)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- try
- {
- if (repo->repoInfo().baseUrlsSize() > 1)
- {
- // store current urls
- std::set<zypp::Url> baseUrls (repo->repoInfo().baseUrlsBegin(), repo->repoInfo().baseUrlsEnd());
-
- // reset url list and store the new one there
- repo->repoInfo().setBaseUrl(zypp::Url(u->value()));
-
- // add the rest of base urls
- for (std::set<zypp::Url>::const_iterator i = baseUrls.begin();
- i != baseUrls.end(); ++i)
- repo->repoInfo().addBaseUrl(*i);
- }
- else
- repo->repoInfo().setBaseUrl(zypp::Url(u->value()));
- }
- catch (const zypp::Exception & excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error ("Cannot set the new URL for source %s (%lld): %s",
- repo->repoInfo().alias().c_str(), id->asInteger()->value(), excpt.msg().c_str());
- return YCPBoolean(false);
- }
-
- return YCPBoolean(true);
-}
-
-/****************************************************************************************
- * @builtin SourceInstallOrder
- *
- * @short not implemented, do not use (Explicitly set an install order.)
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceInstallOrder (const YCPMap& ord)
-{
- /* TODO FIXME
- YCPList args;
- args->add (ord);
-
- //-------------------------------------------------------------------------------------//
- YcpArgLoad decl(__FUNCTION__);
-
- YCPMap & order_map( decl.arg<YT_MAP, YCPMap>() );
-
- if ( ! decl.load( args ) ) {
- return pkgError_bad_args;
- }
- //-------------------------------------------------------------------------------------//
-
- InstSrcManager::InstOrder order;
- order.reserve( order_map->size() );
- bool error = false;
-
- for ( YCPMapIterator it = order_map->begin(); it != order_map->end(); ++it ) {
-
- if ( it.value()->isInteger() ) {
- InstSrc::UniqueID uId( it.value()->asInteger()->value() );
- InstSrcManager::ISrcId source_id( _y2pm.instSrcManager().getSourceByID( uId ) );
- if ( source_id ) {
- if ( source_id->enabled() ) {
- order.push_back( uId ); // finaly ;)
-
- } else {
- y2error ("order map entry '%s:%s': source not enabled",
- it.key()->toString().c_str(),
- it.value()->toString().c_str() );
- error = true;
- }
- } else {
- y2error ("order map entry '%s:%s': bad source id",
- it.key()->toString().c_str(),
- it.value()->toString().c_str() );
- error = true;
- }
- } else {
- y2error ("order map entry '%s:%s': integer value expected",
- it.key()->toString().c_str(),
- it.value()->toString().c_str() );
- error = true;
- }
- }
- if ( error ) {
- return pkgError( Error::E_bad_args );
- }
-
- // store new instorder
- _y2pm.instSrcManager().setInstOrder( order );
-*/
-
-#warning SourceInstallOrder is not implemented
- return YCPBoolean( true );
-}
-
-
-static std::string timestamp ()
-{
- time_t t = time(NULL);
- struct tm * tmp = localtime(&t);
-
- if (tmp == NULL) {
- return "";
- }
-
- char outstr[50];
- if (strftime(outstr, sizeof(outstr), "%Y%m%d-%H%M%S", tmp) == 0) {
- return "";
- }
- return outstr;
-}
-
-/**
- * Take the ?alias=foo part of old_url, if any, and return it,
- * putting the rest to new_url.
- * \throws Exception on malformed URLs I guess
- */
-static std::string removeAlias (const zypp::Url & old_url,
- zypp::Url & new_url)
-{
- std::string alias;
- new_url = old_url;
- zypp::url::ParamMap query = new_url.getQueryStringMap ();
- zypp::url::ParamMap::iterator alias_it = query.find ("alias");
- if (alias_it != query.end ())
- {
- alias = alias_it->second;
- query.erase (alias_it);
- new_url.setQueryStringMap (query);
- }
- return alias;
-}
-
-std::string PkgModuleFunctions::UniqueAlias(const std::string &alias)
-{
- // make a copy
- std::string ret = alias;
-
- unsigned int id = 0;
- while(aliasExists(ret))
- {
- y2milestone("Alias %s already found: %lld", ret.c_str(), logFindAlias(ret));
-
- // the alias already exists - add a counter
- std::ostringstream ostr;
- ostr << alias << "_" << id;
-
- ret = ostr.str();
-
- y2milestone("Using alias %s", ret.c_str());
- ++id;
- }
-
- return ret;
-}
-
-
-/**
- * helper - add "mountoptions=ro" for mountable URL schemes if "mountoptions" option is not empty and
- * "rw" or "ro" option is missing
- */
-zypp::Url addRO(const zypp::Url &url)
-{
- zypp::Url ret(url);
- std::string scheme = zypp::str::toLower(url.getScheme());
-
- if (scheme == "nfs"
- || scheme == "hd"
- || scheme == "smb"
- || scheme == "iso"
- || scheme == "cd"
- || scheme == "dvd"
- )
- {
- const std::string mountoptions = "mountoptions";
- zypp::media::Mount::Options options(url.getQueryParam(mountoptions));
-
- y2debug("Current mountoptions: %s", options.asString().c_str());
-
- // if mountoptions are empty lizypp uses "ro" by default
- // don't override "rw" option from application
- // don't add "ro" if it's already present
- if (!options.empty() && !options.has("rw") && !options.has("ro"))
- {
- options["ro"];
-
- ret.setQueryParam(mountoptions, options.asString());
- y2milestone("Adding read only mount option: '%s' -> '%s'", url.asString().c_str(), ret.asString().c_str());
- }
- }
-
- return ret;
-}
-
-// helper function
-zypp::Url PkgModuleFunctions::shortenUrl(const zypp::Url &url)
-{
- std::string url_path = url.getPathName();
- std::string begin_path;
- std::string end_path;
-
- // try to convert 'http://server/dir1/dir2/dir3/dir4' -> 'http://server/dir1/.../dir4'
- std::string::size_type pos_first = url_path.find("/");
- if (pos_first == 0)
- {
- pos_first = url_path.find("/", 1);
- }
-
- if (pos_first == std::string::npos)
- {
- const int num = 5;
-
- // "/" not found use the beginning and the end part
- // 'http://server/very_long_directory_name' -> 'http://server/very_..._name'
- begin_path = std::string(url_path, 0, num);
- end_path = std::string(url_path, url_path.size() - num - 1, num);
- }
- else
- {
- unsigned int pos_last = url_path.rfind("/");
- if (pos_last == url_path.size() - 1)
- {
- pos_last = url_path.rfind("/", url_path.size() - 1);
- }
-
- if (pos_last == pos_first || pos_last < pos_first)
- {
- const int num = 5;
-
- // "/" not found use the beginning and the end part
- begin_path = std::string(url_path, 0, num);
- end_path = std::string(url_path, url_path.size() - num - 1, num);
- }
- else
- {
- begin_path = std::string(url_path, 0, pos_first + 1);
- end_path = std::string(url_path, pos_last);
- }
- }
-
- std::string new_path = begin_path + "..." + end_path;
- zypp::Url ret(url);
-
- // use the shorter path
- ret.setPathName(new_path);
- // remove query parameters
- ret.setQueryString("");
- // remove fragmet
- ret.setFragment("");
-
- y2milestone("Using shortened URL: '%s' -> '%s'", url.asString().c_str(), ret.asString().c_str());
- return ret;
-}
-
-/** Create a Source and immediately put it into the SourceManager.
- * \return the SourceId
- * \throws Exception if Source creation fails
-*/
-std::vector<zypp::RepoInfo>::size_type
-PkgModuleFunctions::createManagedSource( const zypp::Url & url_r,
- const zypp::Pathname & path_r,
- const bool base_source,
- const std::string& type,
- const std::string &alias_r )
-{
- // parse URL
- y2milestone ("Original URL: %s, product directory: %s", url_r.asString().c_str(), path_r.asString().c_str());
-
- // #158850#c17, if the URL contains an alias, we use that
- zypp::Url url;
-
- std::string alias = removeAlias(url_r, url);
- y2milestone("Alias from URL: '%s'", alias.c_str());
-
-#warning FIXME: use base_source (base_source vs. addon) (will be probably not needed)
-
- // repository type
- zypp::repo::RepoType repotype;
- zypp::RepoManager repomanager = CreateRepoManager();
-
- if (!type.empty())
- {
- try
- {
- // do conversion from the Yast type ("YaST", "YUM", "Plaindir")
- // to libzypp type ("yast", "yum", "plaindir")
- repotype = repotype.parse(yast2zyppType(type));
- }
- catch (zypp::repo::RepoUnknownTypeException &e)
- {
- y2warning("Unknown source type '%s'", type.c_str());
- }
- }
-
- // the type is not specified or is wrong, autoprobe the type
- if (repotype == zypp::repo::RepoType::NONE)
- {
- zypp::Url probe_url(url_r);
-
- if (!path_r.asString().empty())
- {
- zypp::Pathname pth(probe_url.getPathName());
- pth /= path_r;
-
- probe_url.setPathName(pth.asString());
- }
-
- y2milestone("Probing source type: '%s'", probe_url.asString().c_str());
-
- // autoprobe type of the repository
- repotype = ProbeWithCallbacks(probe_url);
- }
-
- y2milestone("Using source type: %s", repotype.asString().c_str());
-
-
- // create source definition object
- zypp::RepoInfo repo;
-
- std::string name;
-
- // set alias and name
- if (alias.empty())
- {
- // alias not set via URL, use the passed alias or the URL path
- if (alias_r.empty())
- {
- // use the last path element in URL
- std::string url_path = url.getPathName();
-
- std::string::size_type pos_begin = url_path.rfind("/");
- std::string::size_type pos_end = std::string::npos;
-
- // ignore the trailing slash
- if (pos_begin == url_path.size() - 1)
- {
- pos_begin = url_path.rfind("/", url_path.size() - 2);
-
- if (pos_begin != std::string::npos)
- {
- pos_end = url_path.size() - pos_begin - 2;
- }
- }
- else
- {
- pos_end = url_path.size() - pos_begin - 1;
- }
-
- // ignore the found slash character
- pos_begin++;
-
- alias = std::string(url_path, pos_begin, pos_end);
-
- y2milestone("Alias from URL path: %s", alias.c_str());
-
- // fallback
- if (alias.empty())
- {
- y2milestone("URL alias is empty using 'Repository'");
- alias = "Repository";
- }
- }
- else
- {
- alias = alias_r;
- }
-
- name = alias;
- }
- else
- {
- name = alias;
- }
-
-
- y2milestone("Name of the repository: '%s'", name.c_str());
-
- // alias must be unique, add a suffix if it's already used
- alias = UniqueAlias(alias);
-
- // add read only mount option to the URL if needed
- url = addRO(url);
-
- bool autorefresh = true;
-
- std::string scheme = zypp::str::toLower(url.getScheme());
- if (scheme == "cd" || scheme == "dvd")
- {
- y2milestone("Disabling autorefresh for CD/DVD repository");
- autorefresh = false;
- }
-
- repo.setAlias(alias);
- repo.setName(name);
- repo.setType(repotype);
- repo.addBaseUrl(url);
- repo.setPath(path_r);
- repo.setEnabled(true);
- repo.setAutorefresh(autorefresh);
-
- // set metadata path (#293428)
- zypp::Pathname metadatapath = repomanager.metadataPath(repo);
- repo.setMetadataPath(metadatapath);
-
- y2milestone("Adding source '%s' (%s, dir: %s)", repo.alias().c_str(), url.asString().c_str(), path_r.asString().c_str());
- // note: exceptions should be caught by the calling code
- RefreshWithCallbacks(repo);
-
- // build cache if needed
- if (!repomanager.isCached(repo))
- {
- y2milestone("Caching source '%s'...", repo.alias().c_str());
- repomanager.buildCache(repo);
- }
-
- repos.push_back(new YRepo(repo));
-
- y2milestone("Added source '%s': '%s', enabled: %s, autorefresh: %s",
- repo.alias().c_str(),
- repo.baseUrlsBegin()->asString().c_str(),
- repo.enabled() ? "true" : "false",
- repo.autorefresh() ? "true" : "false"
- );
-
- // the source is at the end of the list
- return repos.size() - 1;
-}
-
-/****************************************************************************************
- * @builtin RepositoryAdd
- *
- * @short Register a new repository
- * @description
- * Adds a new repository to the internal structures. The repository is only registered,
- * metadata is not downloaded, use Pkg::SourceRefreshNow() for that. The metadata is also loaded
- * automatically when loading the repository content (Pkg::SourceLoad())
- *
- * @param map map with repository parameters: $[ "enabled" : boolean, "autorefresh" : boolean, "name" : string,
- * "alias" : string, "base_urls" : list<string>, "prod_dir" : string, "type" : string ]
- * @return integer Repository ID or nil on error
- **/
-YCPValue PkgModuleFunctions::RepositoryAdd(const YCPMap ¶ms)
-{
- zypp::RepoInfo repo;
-
- // turn on the repo by default
- repo.setEnabled(true);
- // enable autorefresh by default
- repo.setAutorefresh(true);
-
- if (!params->value( YCPString("enabled") ).isNull() && params->value(YCPString("enabled"))->isBoolean())
- {
- repo.setEnabled(params->value(YCPString("enabled"))->asBoolean()->value());
- }
-
- if (!params->value( YCPString("autorefresh") ).isNull() && params->value(YCPString("autorefresh"))->isBoolean())
- {
- repo.setAutorefresh(params->value(YCPString("autorefresh"))->asBoolean()->value());
- }
-
- std::string alias;
-
- if (!params->value( YCPString("alias") ).isNull() && params->value(YCPString("alias"))->isString())
- {
- alias = params->value(YCPString("alias"))->asString()->value();
- }
-
- if (alias.empty())
- {
- alias = timestamp();
-
- // the alias must be unique
- alias = UniqueAlias(alias);
- }
- else
- {
- if (aliasExists(alias))
- {
- ycperror("alias %s already exists", alias.c_str());
- return YCPVoid();
- }
- }
-
- repo.setAlias(alias);
-
- // use the first base URL as a fallback name
- std::string first_url;
-
- if (!params->value( YCPString("base_urls") ).isNull() && params->value(YCPString("base_urls"))->isList())
- {
- YCPList lst(params->value(YCPString("base_urls"))->asList());
-
- for (int index = 0; index < lst->size(); ++index)
- {
- if( ! lst->value(index)->isString() )
- {
- ycperror( "Pkg::RepositoryAdd(): entry not a string at index %d: %s", index, lst->toString().c_str());
- return YCPVoid();
- }
-
- zypp::Url url;
-
- try
- {
- url = lst->value(index)->asString()->value();
- zypp::Url url_new;
-
- std::string name = removeAlias(url, url_new);
-
- if (!name.empty())
- {
- repo.setName(name);
- url = url_new;
- }
-
- // add read only mount option to the URL if needed
- url = addRO(url);
- }
- catch(const zypp::Exception & expt)
- {
- y2error("Invalid URL: %s", expt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(expt));
- return YCPVoid();
- }
-
- if (index == 0)
- {
- first_url = url.asString();
- }
-
- repo.addBaseUrl(url);
- }
- }
- else
- {
- ycperror("Missing \"base_urls\" key in the map");
- return YCPVoid();
- }
-
- // check name parameter
- if (!params->value( YCPString("name") ).isNull() && params->value(YCPString("name"))->isString())
- {
- repo.setName(params->value(YCPString("name"))->asString()->value());
- }
- else
- {
- // if the key "name" is missing and the name hasn't been set by ?alias= in the URL
- // then use the first URL as the name
- if (repo.name().empty())
- {
- repo.setName(first_url);
- }
- }
-
- if (!params->value( YCPString("type") ).isNull() && params->value(YCPString("type"))->isString())
- {
- std::string type = yast2zyppType(params->value(YCPString("type"))->asString()->value());
-
- try
- {
- zypp::repo::RepoType repotype(type);
- repo.setType(repotype);
- }
- catch (zypp::repo::RepoUnknownTypeException &e)
- {
- ycperror("Unknown source type '%s': %s", type.c_str(), e.asString().c_str());
- _last_error.setLastError(ExceptionAsString(e));
- return YCPVoid();
- }
-
- }
-
- if (!params->value( YCPString("prod_dir") ).isNull() && params->value(YCPString("prod_dir"))->isString())
- {
- repo.setPath(params->value(YCPString("prod_dir"))->asString()->value());
- }
-
- // set metadata path (#293428)
- zypp::RepoManager repomanager = CreateRepoManager();
- zypp::Pathname metadatapath = repomanager.metadataPath(repo);
- repo.setMetadataPath(metadatapath);
-
- repos.push_back(new YRepo(repo));
-
- // the new source is at the end of the list
- return YCPInteger(repos.size() - 1);
-}
-
-/****************************************************************************************
- * @builtin SourceCacheCopyTo
- *
- * @short Copy cache data of all installation sources to the target
- * @description
- * Copy cache data of all installation sources to the target located below 'dir'.
- * To be called at end of initial installation.
- *
- * @param string dir Root directory of target.
- * @return boolean true on success
- **/
-YCPValue
-PkgModuleFunctions::SourceCacheCopyTo (const YCPString& dir)
-{
- // error message (followed by detailed description)
- const std::string msg = _("Error: Cannot copy the cache to the target directory\n");
-
- std::string d = dir->value();
- y2milestone("Copying source cache to '%s'...", d.c_str());
-
- if (d.empty())
- {
- y2error("Empty parameter in Pkg::SourceCacheCopyTo()!");
- return YCPBoolean(false);
- }
-
- std::string target = d + "/var/cache";
-
- // create the target dir
- const char* argv[] =
- {
- "mkdir",
- // create parent dir
- "-p",
- // finish parameter list
- "--",
- // target
- target.c_str(),
- NULL
- };
-
- // discard stderr, no pty, stderr_fd = -1, use the default locale
- zypp::ExternalProgram prog(argv, zypp::ExternalProgram::Discard_Stderr, false, -1, true);
-
- int code = prog.close();
-
- if (code)
- {
- // error message (followed by directory name)
- _last_error.setLastError(msg + _("Cannot create directory ") + target);
- y2error("Cannot create target directory %s", target.c_str());
- return YCPBoolean(false);
- }
-
- // copy /var/cache/zypp to the target system
- const char* argv2[] =
- {
- "cp",
- // preserve time stamps
- "-a",
- // recursive
- "-r",
- // finish parameter list
- "--",
- // source
- "/var/cache/zypp",
- // target
- target.c_str(),
- NULL
- };
-
- // discard stderr, no pty, stderr_fd = -1, use the default locale
- zypp::ExternalProgram prog2(argv2, zypp::ExternalProgram::Discard_Stderr, false, -1, true);
-
- int code2 = prog2.close();
-
- if (code2)
- {
- // error message
- _last_error.setLastError(msg + _("Copying failed"));
- y2error("Cannot copy /var/cache/zypp to %s", d.c_str());
- }
-
- return YCPBoolean(!code2);
-}
-
-/****************************************************************************************
- * @builtin SourceScan
- * @short Scan a Source Media
- * @description
- * Load all InstSrces found at media_url, i.e. all sources mentioned in /media.1/products.
- * If no /media.1/products is available, InstSrc is expected to be located directly
- * below media_url (product_dir: /).
- *
- * If a product_dir is provided, only the InstSrc located at media_url/product_dir is loaded.
- *
- * In contrary to @ref SourceCreate, InstSrces are loaded into the InstSrcManager,
- * but not enabled (packages and selections are not provided to the PackageManager),
- * and the SrcIds of <b>all</b> InstSrces found are returned.
- *
- * @param string url The media to scan.
- * @optarg string product_dir Restrict scan to a certain InstSrc located in media_url/product_dir.
- *
- * @return list<integer> list of SrcIds (integer).
- **/
-YCPValue
-PkgModuleFunctions::SourceScan (const YCPString& media, const YCPString& pd)
-{
- zypp::Url url;
-
- try {
- url = zypp::Url(media->value ());
- }
- catch(const zypp::Exception & expt )
- {
- y2error ("Invalid URL: %s", expt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(expt));
- return YCPList();
- }
-
- zypp::Pathname pn(pd->value ());
-
- YCPList ids;
- std::vector<zypp::RepoInfo>::size_type id;
-
- if ( pd->value().empty() ) {
-
- // scan all sources
- zypp::MediaProductSet products;
-
- try
- {
- y2milestone("Scanning products in %s ...", url.asString().c_str());
- ScanProductsWithCallBacks(url);
- products = available_products;
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("Scanning products for '%s' has failed"
- , url.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- return ids;
- }
-
- if( products.empty() )
- {
- // no products found, use the base URL instead
- zypp::MediaProductEntry entry;
- products.insert(entry);
- }
-
- for( zypp::MediaProductSet::const_iterator it = products.begin();
- it != products.end() ; ++it )
- {
- try
- {
- y2milestone("Using product %s in directory %s", it->_name.c_str(), it->_dir.c_str());
- id = createManagedSource(url, it->_dir, false, "", it->_name);
- ids->add( YCPInteger(id) );
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("SourceScan for '%s' product '%s' has failed"
- , url.asString().c_str(), pn.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- }
- }
- } else {
- y2debug("Creating source...");
-
- try
- {
- id = createManagedSource(url, pn, false, "", "");
- ids->add( YCPInteger(id) );
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("SourceScan for '%s' product '%s' has failed"
- , url.asString().c_str(), pn.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- }
- }
-
- y2milestone("Found sources: %s", ids->toString().c_str() );
-
- return ids;
-}
-
-/****************************************************************************************
- * @builtin SourceCreate
+/* ------------------------------------------------------------------------------
+ * Copyright (c) 2007 Novell, Inc. All Rights Reserved.
*
- * @short Create a Source
- * @description
- * Load and enable all InstSrces found at media_url, i.e. all sources mentioned in /media.1/products.
- * If no /media.1/products is available, InstSrc is expected to be located directly below
- * media_url (product_dir: /).
*
- * If a product_dir is provided, only the InstSrc located at media_url/product_dir is loaded
- * and enabled.
+ * This program is free software; you can redistribute it and/or modify it under
+ * the terms of version 2 of the GNU General Public License as published by the
+ * Free Software Foundation.
*
- * @param string url The media to scan.
- * @optarg string product_dir Restrict scan to a certain InstSrc located in media_url/product_dir.
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+ * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
- * @return integer The source_id of the first InstSrc found on the media.
- **/
-YCPValue
-PkgModuleFunctions::SourceCreate (const YCPString& media, const YCPString& pd)
-{
- // not base product, autoprobe source type
- return SourceCreateEx (media, pd, false, YCPString(""));
-}
-
-YCPValue
-PkgModuleFunctions::SourceCreateBase (const YCPString& media, const YCPString& pd)
-{
- // base product, autoprobe source type
- return SourceCreateEx (media, pd, true, YCPString(""));
-}
+ * You should have received a copy of the GNU General Public License along with
+ * this program; if not, contact Novell, Inc.
+ *
+ * To contact Novell about this file by physical or electronic mail, you may find
+ * current contact information at www.novell.com.
+ * ------------------------------------------------------------------------------
+ */
-/**
- * @builtin SourceCreateType
- * @short Create source of required type
- * @description
- * Create a source without autoprobing the source type. This builtin should be used only for "Plaindir" sources, because Plaindir sources are not automatically probed in SourceCreate() builtin.
- * @param media URL of the source
- * @param pd product directory (if empty the products will be searched)
- * @param type type of the source ("YaST", "YUM" or "Plaindir")
+/*
+ File: $Id:$
+ Author: Ladislav Slezák <lslezak(a)novell.com>
+ Summary: Functions for reading repository properties
*/
-YCPValue
-PkgModuleFunctions::SourceCreateType (const YCPString& media, const YCPString& pd, const YCPString& type)
-{
- // not base product, autoprobe source type
- return SourceCreateEx (media, pd, false, type);
-}
-
-YCPValue
-PkgModuleFunctions::SourceCreateEx (const YCPString& media, const YCPString& pd, bool base, const YCPString& source_type)
-{
- y2debug("Creating source...");
-
- zypp::Pathname pn(pd->value ());
-
- zypp::Url url;
-
- try {
- url = zypp::Url(media->value ());
- }
- catch(const zypp::Exception & expt )
- {
- y2error ("Invalid URL: %s", expt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(expt));
- return YCPInteger (-1LL);
- }
-
-
- YCPList ids;
- std::vector<zypp::RepoInfo>::size_type ret = -1;
-
- const std::string type = source_type->value();
-
- if ( pd->value().empty() ) {
- // scan all sources
- zypp::MediaProductSet products;
-
- try {
- ScanProductsWithCallBacks(url);
- products = available_products;
- }
- catch ( const zypp::Exception& excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error( "Cannot read the product list from the media" );
- return YCPInteger(-1LL);
- }
-
- if( products.empty() )
- {
- // no products found, use the base URL instead
- zypp::MediaProductEntry entry ;
- products.insert( entry );
- }
-
- for( zypp::MediaProductSet::const_iterator it = products.begin();
- it != products.end() ; ++it )
- {
- try
- {
- std::vector<zypp::RepoInfo>::size_type id = createManagedSource(url, it->_dir, base, type, it->_name);
- YRepo_Ptr repo = logFindRepository(id);
-
- LoadResolvablesFrom(repo->repoInfo());
-
- // return the id of the first product
- if ( it == products.begin() )
- ret = id;
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("SourceCreate for '%s' product '%s' has failed"
- , url.asString().c_str(), pn.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- return YCPInteger(-1LL);
- }
- }
- } else {
- y2debug("Creating source...");
-
- try
- {
- ret = createManagedSource(url, pn, base, type, "");
-
- YRepo_Ptr repo = logFindRepository(ret);
- repo->repoInfo().setEnabled(true);
-
- LoadResolvablesFrom(repo->repoInfo());
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("SourceCreate for '%s' product '%s' has failed"
- , url.asString().c_str(), pn.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- }
- }
+#include <Callbacks.h>
+#include <Callbacks.YCP.h>
- PkgFreshen();
- return YCPInteger(repos.size() - 1);
-}
+#include <PkgModule.h>
+#include <PkgModuleFunctions.h>
+#include <zypp/Product.h>
/****************************************************************************************
- * @builtin SourceSetEnabled
+ * @builtin SourceGetCurrent
+ *
+ * @short Return the list of all InstSrc Ids.
*
- * @short Set the default activation state of an InsrSrc.
- * @param integer SrcId Specifies the InstSrc.
- * @param boolean enabled Default activation state of source.
+ * @param boolean enabled_only If true, or omitted, return the Ids of all enabled InstSrces.
+ * If false, return the Ids of all known InstSrces.
*
- * @return boolean
+ * @return list<integer> list of SrcIds (integer)
**/
YCPValue
-PkgModuleFunctions::SourceSetEnabled (const YCPInteger& id, const YCPBoolean& e)
+PkgModuleFunctions::SourceGetCurrent (const YCPBoolean& enabled)
{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- // no change required
- bool enable = e->value();
- if ((enable && repo->repoInfo().enabled())
- || (!enable && !repo->repoInfo().enabled()))
- return YCPBoolean(true);
-
- bool success = true;
+ YCPList res;
- try
+ std::vector<YRepo_Ptr>::size_type index = 0;
+ for( std::vector<YRepo_Ptr>::const_iterator it = repos.begin(); it != repos.end() ; ++it, ++index )
{
- repo->repoInfo().setEnabled(enable);
-
- // add/remove resolvables
- if (enable)
+ // ignore disabled sources if requested
+ if (enabled->value())
{
- // load resolvables only when they are missing
- if (!AnyResolvableFrom(repo->repoInfo().alias()))
+ // Note: enabled() is tribool!
+ if ((*it)->repoInfo().enabled())
+ {
+ }
+ else if (!(*it)->repoInfo().enabled())
+ {
+ continue;
+ }
+ else
{
- success = LoadResolvablesFrom(repo->repoInfo());
+ continue;
}
}
- else
+
+ // ignore deleted sources
+ if ((*it)->isDeleted())
{
- // the source has been disabled, remove resolvables from the pool
- RemoveResolvablesFrom(repo->repoInfo().alias());
+ continue;
}
- PkgFreshen();
- }
- catch (const zypp::Exception& excpt)
- {
- std::string alias = repo->repoInfo().alias();
- y2error ("Error for '%s': %s", alias.c_str(), excpt.asString().c_str());
- _last_error.setLastError(alias + ": " + ExceptionAsString(excpt));
- success = false;
+ res->add( YCPInteger(index) );
}
- return YCPBoolean(success);
-}
-
-/****************************************************************************************
- * @builtin SourceSetAutorefresh
- *
- * @short Set whether this source should automaticaly refresh it's
- * meta data when it gets enabled. (default true, if not CD/DVD)
- * @param integer SrcId Specifies the InstSrc.
- * @param boolean enabled Whether autorefresh should be turned on or off.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceSetAutorefresh (const YCPInteger& id, const YCPBoolean& e)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- repo->repoInfo().setAutorefresh(e->value());
-
- return YCPBoolean( true );
+ return res;
}
-/****************************************************************************************
- * @builtin SourceFinish
- * @short Disable an Installation Source
- * @param integer SrcId Specifies the InstSrc.
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceFinish (const YCPInteger& id)
-{
- return SourceSetEnabled(id, false);
-}
+/////////////////////////////////////////////////////////////////////////////////////////
+// Query individual sources
+/////////////////////////////////////////////////////////////////////////////////////////
/****************************************************************************************
- * @builtin SourceRefreshNow
- * @short Attempt to immediately refresh a Source
- * @description
- * The InsrSrc will be encouraged to check and refresh all metadata
- * cached on disk.
- *
- * @param integer SrcId Specifies the InstSrc.
+ * @builtin SourceGeneralData
*
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceRefreshNow (const YCPInteger& id)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- try
- {
- zypp::RepoManager repomanager = CreateRepoManager();
- y2milestone("Refreshing metadata '%s'", repo->repoInfo().alias().c_str());
- RefreshWithCallbacks(repo->repoInfo());
-
- y2milestone("Caching source '%s'...", repo->repoInfo().alias().c_str());
- repomanager.buildCache(repo->repoInfo());
- }
- catch ( const zypp::Exception & expt )
- {
- y2error ("Error while refreshing the source: %s", expt.asString().c_str());
- _last_error.setLastError(repo->repoInfo().alias() + ": " + ExceptionAsString(expt));
- return YCPBoolean(false);
- }
-
- return YCPBoolean( true );
-}
-
-/****************************************************************************************
- * @builtin SourceDelete
- * @short Delete a Source
+ * @short Get general data about the source
* @description
- * Delete an InsrSrc. The InsrSrc together with all metadata cached on disk
- * is removed. The SrcId passed becomes invalid (other SrcIds stay valid).
- *
- * @param integer SrcId Specifies the InstSrc.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceDelete (const YCPInteger& id)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- bool success = true;
-
- try
- {
- // the resolvables cannot be used anymore, remove them
- RemoveResolvablesFrom(repo->repoInfo().alias());
-
- // update 'repos'
- repo->setDeleted();
-
- PkgFreshen();
- }
- catch (const zypp::Exception& excpt)
- {
- std::string alias = repo->repoInfo().alias();
- y2error ("Error for '%s': %s", alias.c_str(), excpt.asString().c_str());
- _last_error.setLastError(alias + ": " + ExceptionAsString(excpt));
- success = false;
- }
-
- return YCPBoolean(success);
-}
-
-/****************************************************************************************
- * @builtin SourceEditGet
+ * Return general data about the source as a map:
*
- * @short Get state of Sources
- * @description
- * Return a list of states for all known InstSources sorted according to the
- * source priority (highest first). A source state is a map:
+ * <code>
* $[
- * "SrcId" : YCPInteger,
- * "enabled" : YCPBoolean
- * "autorefresh": YCPBoolean
+ * "enabled" : YCPBoolean,
+ * "autorefresh": YCPBoolean,
+ * "product_dir": YCPString,
+ * "type" : YCPString,
+ * "url" : YCPString (without password, but see SourceURL),
+ * "alias" : YCPString,
+ * "name" : YCPString,
* ];
*
- * @return list<map> list of source states (map)
- **/
-YCPValue
-PkgModuleFunctions::SourceEditGet ()
-{
- YCPList ret;
-
- unsigned long index = 0;
- for( std::vector<YRepo_Ptr>::const_iterator it = repos.begin(); it != repos.end(); ++it, ++index)
- {
- if (!(*it)->isDeleted())
- {
- YCPMap src_map;
-
- src_map->add(YCPString("SrcId"), YCPInteger(index));
- // Note: enabled() is tribool
- src_map->add(YCPString("enabled"), YCPBoolean((*it)->repoInfo().enabled()));
- // Note: autorefresh() is tribool
- src_map->add(YCPString("autorefresh"), YCPBoolean((*it)->repoInfo().autorefresh()));
- src_map->add(YCPString("name"), YCPString((*it)->repoInfo().name()));
-
- ret->add(src_map);
- }
- }
-
- return ret;
-}
-
-/****************************************************************************************
- * @builtin SourceEditSet
- *
- * @short Configure properties of installation sources
- * @description
- * Set states of installation sources. Note: Enabling/disabling a source does not
- * (un)load the packages from the source! Use SourceSetEnabled() if you need to refresh
- * the packages in the pool.
- *
- * @param list source_states List of source states. Same format as returned by
- * @see SourceEditGet.
- *
- * @return boolean
+ * </code>
+ * @param integer SrcId Specifies the InstSrc to query.
+ * @return map
**/
YCPValue
-PkgModuleFunctions::SourceEditSet (const YCPList& states)
+PkgModuleFunctions::SourceGeneralData (const YCPInteger& id)
{
- bool error = false;
-
- for (int index = 0; index < states->size(); index++ )
- {
- if( ! states->value(index)->isMap() )
- {
- ycperror( "Pkg::SourceEditSet, entry not a map at index %d", index);
- error = true;
- continue;
- }
-
- YCPMap descr = states->value(index)->asMap();
-
- if (descr->value( YCPString("SrcId") ).isNull() || !descr->value(YCPString("SrcId"))->isInteger())
- {
- ycperror( "Pkg::SourceEditSet, SrcId not defined for a source description at index %d", index);
- error = true;
- continue;
- }
-
- std::vector<YRepo_Ptr>::size_type id = descr->value( YCPString("SrcId") )->asInteger()->value();
+ YCPMap data;
- YRepo_Ptr repo = logFindRepository(id);
+ YRepo_Ptr repo = logFindRepository(id->value());
if (!repo)
- {
- ycperror( "Pkg::SourceEditSet, source %d not found", index);
- error = true;
- continue;
- }
-
- // now, we have the source
- if( ! descr->value( YCPString("enabled")).isNull() && descr->value(YCPString("enabled"))->isBoolean ())
- {
- bool enable = descr->value(YCPString("enabled"))->asBoolean ()->value();
-
- if (repo->repoInfo().enabled() != enable)
- {
- ycpwarning("Pkg::SourceEditSet() does not refresh the pool (src: %zd, state: %s)", id, enable ? "disabled -> enabled" : "enabled -> disabled");
- }
+ return YCPVoid ();
- y2debug("set enabled: %d", enable);
- repo->repoInfo().setEnabled(enable);
- }
+ // convert type to the old strings ("YaST", "YUM" or "Plaindir")
+ std::string srctype = zypp2yastType(repo->repoInfo().type().asString());
- if( !descr->value(YCPString("autorefresh")).isNull() && descr->value(YCPString("autorefresh"))->isBoolean ())
+ data->add( YCPString("enabled"), YCPBoolean(repo->repoInfo().enabled()));
+ data->add( YCPString("autorefresh"), YCPBoolean(repo->repoInfo().autorefresh()));
+ data->add( YCPString("type"), YCPString(srctype));
+ data->add( YCPString("product_dir"), YCPString(repo->repoInfo().path().asString()));
+
+ // check if there is an URL
+ if (repo->repoInfo().baseUrlsBegin() != repo->repoInfo().baseUrlsEnd())
{
- bool autorefresh = descr->value(YCPString("autorefresh"))->asBoolean()->value();
- y2debug("set autorefresh: %d", autorefresh);
- repo->repoInfo().setAutorefresh( autorefresh );
+ data->add( YCPString("url"), YCPString(repo->repoInfo().baseUrlsBegin()->asString()));
}
- if( !descr->value(YCPString("name")).isNull() && descr->value(YCPString("name"))->isString())
+ data->add( YCPString("alias"), YCPString(repo->repoInfo().alias()));
+ data->add( YCPString("name"), YCPString(repo->repoInfo().name()));
+
+ YCPList base_urls;
+ for( zypp::RepoInfo::urls_const_iterator it = repo->repoInfo().baseUrlsBegin(); it != repo->repoInfo().baseUrlsEnd(); ++it)
{
- // rename the source
- y2debug("set name: %s", descr->value(YCPString("name"))->asString()->value().c_str());
- repo->repoInfo().setName(descr->value(YCPString("name"))->asString()->value());
+ base_urls->add(YCPString(it->asString()));
}
+ data->add( YCPString("base_urls"), base_urls);
-#warning SourceEditSet ordering not implemented yet
- }
+ data->add( YCPString("mirror_list"), YCPString(repo->repoInfo().mirrorListUrl().asString()));
- PkgFreshen();
- return YCPBoolean( !error );
+ return data;
}
-/////////////////////////////////////////////////////////////////////////////////////////
-//
-// DEPRECATED
-//
-/////////////////////////////////////////////////////////////////////////////////////////
-
-/****************************************************************************************
- * Pkg::SourceRaisePriority (integer SrcId) -> bool
- *
- * Raise priority of source.
- *
- * @param SrcId Specifies the InstSrc.
+/******************************************************************************
+ * @builtin SourceURL
*
- * @return bool
+ * @short Get full source URL, including password
+ * @param integer SrcId Specifies the InstSrc to query.
+ * @return string or nil on failure
**/
YCPValue
-PkgModuleFunctions::SourceRaisePriority (const YCPInteger& id)
+PkgModuleFunctions::SourceURL (const YCPInteger& id)
{
-#warning SourceRaisePriority is not implemented
- y2warning("SourceRaisePriority is NOT implemented");
-/* zypp::Source_Ref src;
-
- try {
- src = logFindRepository(id->value());
- }
- catch (const zypp::Exception& excpt)
- {
- return YCPBoolean(false);
- }
-
- // raise priority by one
- src.setPriority(src.priority() + 1);
-*/
-
- return YCPBoolean( true );
-}
+ const YRepo_Ptr repo = logFindRepository(id->value());
+ if (!repo)
+ return YCPVoid();
-/****************************************************************************************
- * Pkg::SourceLowerPriority (integer SrcId) -> void
- *
- * Lower priority of source.
- *
- * @param SrcId Specifies the InstSrc.
- *
- * @return bool
- */
-YCPValue
-PkgModuleFunctions::SourceLowerPriority (const YCPInteger& id)
-{
-#warning SourceLowerPriority is not implemented
- y2warning("SourceLowerPriority is NOT implemented");
-/*
- zypp::Source_Ref src;
+ std::string url;
- try {
- src = logFindRepository(id->value());
- }
- catch (const zypp::Exception& excpt)
+ if (repo->repoInfo().baseUrlsBegin() != repo->repoInfo().baseUrlsEnd())
{
- return YCPBoolean(false);
+ // #186842
+ url = repo->repoInfo().baseUrlsBegin()->asCompleteString();
}
- // lower priority by one
- src.setPriority(src.priority() - 1);
-*/
- return YCPBoolean( true );
+ return YCPString(url);
}
/****************************************************************************************
- * Pkg::SourceSaveRanks () -> boolean
+ * @builtin SourceMediaData
+ * @short Return media data about the source
+ * @description
+ * Return media data about the source as a map:
*
- * @short Obsoleted function, do not use
- * @return boolean true
- **/
-YCPValue
-PkgModuleFunctions::SourceSaveRanks ()
-{
- y2error( "SourceSaveRanks not implemented" );
-
- return YCPBoolean( true );
-}
-
-/****************************************************************************************
- * @builtin SourceMoveDownloadArea
+ * <code>
+ * $["media_count": YCPInteger,
+ * "media_id" : YCPString,
+ * "media_vendor" : YCPString,
+ * "url" : YCPString,
+ * ];
+ * </code>
*
- * @short Move download area of CURL-based sources to specified directory
- * @param path specifies the path to move the download area to
- * @return boolean
+ * @param integer SrcId Specifies the InstSrc to query.
+ * @return map
**/
YCPValue
-PkgModuleFunctions::SourceMoveDownloadArea (const YCPString & path)
+PkgModuleFunctions::SourceMediaData (const YCPInteger& id)
{
- try
- {
- y2milestone("Moving download area of all sources to %s", path->value().c_str());
- zypp::media::MediaManager manager;
- manager.setAttachPrefix(path->value());
- }
- catch (zypp::Exception & excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error("Pkg::SourceMoveDownloadArea has failed: %s", excpt.msg().c_str());
- return YCPBoolean(false);
- }
-
- y2milestone( "Download areas moved");
+ YCPMap data;
+ YRepo_Ptr repo = logFindRepository(id->value());
+ if (!repo)
+ return YCPVoid ();
- return YCPBoolean(true);
-}
+ std::string alias = repo->repoInfo().alias();
+ bool found_resolvable = false;
+ int max_medium = 1;
-/*
- * A helper function - remove all resolvables from the repository from the pool
- */
-void PkgModuleFunctions::RemoveResolvablesFrom(const std::string &alias)
-{
- // remove the resolvables if they have been loaded
- // FIXME: can be implemented better? we need a ResStore object for removing,
- // which means search for a resolvable in the pool and get the Repository
- // object which can be asked for all resolvables in it
for (zypp::ResPool::const_iterator it = zypp_ptr()->pool().begin()
; it != zypp_ptr()->pool().end()
; ++it)
{
if (it->resolvable()->repository().info().alias() == alias)
{
- y2milestone("Removing all resolvables from '%s' from the pool...", alias.c_str());
- zypp_ptr()->removeResolvables(it->resolvable()->repository().resolvables());
- break;
+ int medium = it->resolvable()->mediaNr();
+
+ if (medium > max_medium)
+ {
+ max_medium = medium;
+ }
}
}
-}
-/*
- * A helper function - is there any resolvable from the repository in the pool?
- */
-bool PkgModuleFunctions::AnyResolvableFrom(const std::string &alias)
-{
- for (zypp::ResPool::const_iterator it = zypp_ptr()->pool().begin()
- ; it != zypp_ptr()->pool().end()
- ; ++it)
+ if (found_resolvable)
{
- if (it->resolvable()->repository().info().alias() == alias)
- {
- return true;
- }
+ data->add( YCPString("media_count"), YCPInteger(max_medium));
+ }
+ else
+ {
+ y2error("No resolvable from repository '%s' found, cannot get number of media (use Pkg::SourceLoad() to load the resolvables)", alias.c_str());
}
- return false;
-}
-
-/*
- * A helper function - load resolvable from the repository into the pool
- * Warning: Use AnyResolvableFrom() method for checing if the resolvables might be already loaded
- */
-bool PkgModuleFunctions::LoadResolvablesFrom(const zypp::RepoInfo &repoinfo)
-{
- bool success = true;
- unsigned int size_start = zypp_ptr()->pool().size();
- y2milestone("Loading resolvables from '%s', pool size at start: %d", repoinfo.alias().c_str(), size_start);
+ y2warning("Pkg::SourceMediaData() doesn't return \"media_id\" and \"media_vendor\" values anymore.");
- try
+ // SourceMediaData returns URLs without password
+ if (repo->repoInfo().baseUrlsBegin() != repo->repoInfo().baseUrlsEnd())
{
- zypp::RepoManager repomanager = CreateRepoManager();
+ data->add( YCPString("url"), YCPString(repo->repoInfo().baseUrlsBegin()->asString()));
- // build cache if needed
- if (!repomanager.isCached(repoinfo))
+ // add all base URLs
+ YCPList base_urls;
+ for( zypp::RepoInfo::urls_const_iterator it = repo->repoInfo().baseUrlsBegin(); it != repo->repoInfo().baseUrlsEnd(); ++it)
{
- zypp::RepoStatus raw_metadata_status = repomanager.metadataStatus(repoinfo);
- if (raw_metadata_status.empty())
- {
- y2milestone("Missing metadata for source '%s', downloading...", repoinfo.alias().c_str());
- RefreshWithCallbacks(repoinfo);
- }
-
- y2milestone("Caching source '%s'...", repoinfo.alias().c_str());
- repomanager.buildCache(repoinfo);
+ base_urls->add(YCPString(it->asString()));
}
-
- zypp::Repository repository = repomanager.createFromCache(repoinfo);
- const zypp::ResStore &store = repository.resolvables();
-
- // load resolvables
- zypp_ptr()->addResolvables(store);
-
- y2milestone("Loaded %zd resolvables", store.size());
- }
- catch(const zypp::repo::RepoNotCachedException &excpt )
- {
- std::string alias = repoinfo.alias();
- y2error ("Resolvables from '%s' havn't been loaded: %s", alias.c_str(), excpt.asString().c_str());
- _last_error.setLastError("'" + alias + "': " + ExceptionAsString(excpt));
- success = false;
-
- // FIXME ??
- /*
- // disable the source
- y2error("Disabling source %s", url.c_str());
- repo->disable();
- */
- }
- catch (const zypp::Exception& excpt)
- {
- std::string alias = repoinfo.alias();
- y2internal("Error: Loading resolvables failed: %s", ExceptionAsString(excpt).c_str());
- _last_error.setLastError("'" + alias + "': " + ExceptionAsString(excpt));
- success = false;
+ data->add( YCPString("base_urls"), base_urls);
}
- unsigned int size_end = zypp_ptr()->pool().size();
- y2milestone("Pool size at end: %d (loaded %d resolvables)", size_end, size_end - size_start);
- return success;
+ return data;
}
/****************************************************************************************
- * @builtin RepositoryProbe
+ * @builtin SourceProductData
+ * @short Return Product data about the source
+ * @param integer SrcId Specifies the InstSrc to query.
+ * @description
+ * Product data about the source as a map:
+ *
+ * <code>
+ * $[
+ * "label" : YCPString,
+ * "vendor" : YCPString,
+ * "productname" : YCPString,
+ * "productversion" : YCPString,
+ * "relnotesurl" : YCPString,
+ * ];
+ * </code>
*
- * @short Probe type of the repository
- * @param url specifies the path to the repository
- * @param prod_dir product directory (if empty the url is probed directly)
- * @return string repository type ("NONE" if type could be determined, nil if an error occurred (e.g. resolving the hostname)
+ * @return map
**/
-YCPValue PkgModuleFunctions::RepositoryProbe(const YCPString& url, const YCPString& prod_dir)
+YCPValue
+PkgModuleFunctions::SourceProductData (const YCPInteger& src_id)
{
- y2milestone("Probing repository type: '%s'...", url->value().c_str());
- zypp::RepoManager repomanager = CreateRepoManager();
- std::string ret;
+ YCPMap ret;
try
{
- zypp::Url probe_url(url->value());
-
- // add the product directory
- std::string prod = prod_dir->value();
+ // find a product for the given source
+ zypp::ResPool::byKind_iterator it = zypp_ptr()->pool().byKindBegin(zypp::ResTraits<zypp::Product>::kind);
- if (!prod.empty())
+ for( ; it != zypp_ptr()->pool().byKindEnd(zypp::ResTraits<zypp::Product>::kind) ; ++it)
{
- // add "/" at the begining if it's missing
- if (std::string(prod, 0, 1) != "/")
+ zypp::Product::constPtr product = boost::dynamic_pointer_cast<const zypp::Product>( it->resolvable() );
+
+ if( logFindAlias(product->repository().info().alias()) == src_id->value() )
{
- prod = "/" + prod;
- }
+ ret->add( YCPString("label"), YCPString( product->summary() ) );
+ ret->add( YCPString("vendor"), YCPString( product->vendor() ) );
+ ret->add( YCPString("productname"), YCPString( product->name() ) );
+ ret->add( YCPString("productversion"), YCPString( product->edition().version() ) );
+ ret->add( YCPString("relnotesurl"), YCPString( product->releaseNotesUrl().asString()));
- // merge the URL path and the product path
- std::string path = probe_url.getPathName();
- path += prod;
+ #warning SourceProductData not finished
+ /*
+ data->add( YCPString("datadir"), YCPString( descr->content_datadir().asString() ) );
+ TODO (?): "baseproductname", "baseproductversion", "defaultbase", "architectures",
+ "requires", "linguas", "labelmap", "language", "timezone", "descrdir", "datadir"
+ */
- y2milestone("Using probing path: %s", path.c_str());
- probe_url.setPathName(path);
+ break;
+ }
}
- // add "ro" mount option
- probe_url = addRO(probe_url);
-
- // autoprobe type of the repository
- zypp::repo::RepoType repotype = ProbeWithCallbacks(probe_url);
-
- ret = zypp2yastType(repotype.asString());
- y2milestone("Detected type: '%s'...", ret.c_str());
+ if( it == zypp_ptr()->pool().byKindEnd(zypp::ResTraits<zypp::Product>::kind) )
+ {
+ y2error ("Product for source '%lld' not found", src_id->value());
+ }
}
- catch (const zypp::Exception& excpt)
+ catch (...)
{
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error( "Cannot detect the repository type" );
- return YCPVoid();
}
- return YCPString(ret);
+ return ret;
}
/****************************************************************************************
- * @builtin RepositoryScan
- *
- * @short Scan available products in the repository
- * @param url specifies the path to the repository
- * @return list<list<string>> list of the products: [ [ <product_name_1> <directory_1> ], ...]
+ * @builtin SourceProduct
+ * @short Obsoleted function, do not use, see SourceProductData builtin
+ * @deprecated
+ * @param integer
+ * @return map empty map
**/
-YCPValue PkgModuleFunctions::RepositoryScan(const YCPString& url)
+YCPValue
+PkgModuleFunctions::SourceProduct (const YCPInteger& id)
{
- zypp::MediaProductSet products;
-
- try
- {
- zypp::Url baseurl(url->value());
-
- baseurl = addRO(baseurl);
-
- ScanProductsWithCallBacks(baseurl);
- products = available_products;
- }
- catch ( const zypp::Exception& excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error( "Cannot read the product list from the media" );
- return YCPList();
- }
-
- YCPList ret;
-
- for( zypp::MediaProductSet::const_iterator it = products.begin();
- it != products.end() ; ++it )
- {
- YCPList prod;
-
- // add product directory
- prod.add(YCPString(it->_name));
- // add product name
- prod.add(YCPString(it->_dir.asString()));
-
- ret.add(prod);
- }
-
- y2milestone("Found products: %s", ret->toString().c_str());
-
- return ret;
+ /* TODO FIXME */
+ y2error("Pkg::SourceProduct() is obsoleted, use Pkg::SourceProductData() instead!");
+ return YCPMap();
}
-// convert libzypp type to yast strings ("YaST", "YUM" or "Plaindir")
-std::string PkgModuleFunctions::zypp2yastType(const std::string &type)
+/****************************************************************************************
+ * @builtin SourceEditGet
+ *
+ * @short Get state of Sources
+ * @description
+ * Return a list of states for all known InstSources sorted according to the
+ * source priority (highest first). A source state is a map:
+ * $[
+ * "SrcId" : YCPInteger,
+ * "enabled" : YCPBoolean
+ * "autorefresh": YCPBoolean
+ * ];
+ *
+ * @return list<map> list of source states (map)
+ **/
+YCPValue
+PkgModuleFunctions::SourceEditGet ()
{
- std::string ret(type);
+ YCPList ret;
- if (type_conversion_table.empty())
+ unsigned long index = 0;
+ for( std::vector<YRepo_Ptr>::const_iterator it = repos.begin(); it != repos.end(); ++it, ++index)
{
- // initialize the conversion map
- type_conversion_table["rpm-md"] = "YUM";
- type_conversion_table["yast2"] = "YaST";
- type_conversion_table["plaindir"] = "Plaindir";
- type_conversion_table["NONE"] = "NONE";
- }
+ if (!(*it)->isDeleted())
+ {
+ YCPMap src_map;
- std::map<std::string,std::string>::const_iterator it = type_conversion_table.find(type);
+ src_map->add(YCPString("SrcId"), YCPInteger(index));
+ // Note: enabled() is tribool
+ src_map->add(YCPString("enabled"), YCPBoolean((*it)->repoInfo().enabled()));
+ // Note: autorefresh() is tribool
+ src_map->add(YCPString("autorefresh"), YCPBoolean((*it)->repoInfo().autorefresh()));
+ src_map->add(YCPString("name"), YCPString((*it)->repoInfo().name()));
- // found in the conversion table
- if (it != type_conversion_table.end())
- {
- ret = it->second;
- }
- else
- {
- y2error("Cannot convert type '%s'", type.c_str());
+ ret->add(src_map);
+ }
}
return ret;
}
-std::string PkgModuleFunctions::yast2zyppType(const std::string &type)
-{
- // do conversion from the Yast type ("YaST", "YUM", "Plaindir")
- // to libzypp type ("yast", "yum", "plaindir")
- // we can simply use toLower instead of a conversion table
- // in this case
- return zypp::str::toLower(type);
-}
-
Copied: trunk/pkg-bindings/src/Source_Installation.cc (from r42708, trunk/pkg-bindings/src/Source.cc)
URL: http://svn.opensuse.org/viewcvs/yast/trunk/pkg-bindings/src/Source_Installa…
==============================================================================
--- trunk/pkg-bindings/src/Source.cc (original)
+++ trunk/pkg-bindings/src/Source_Installation.cc Thu Dec 6 07:56:58 2007
@@ -1,2671 +1,137 @@
-/*---------------------------------------------------------------------\
-| |
-| __ __ ____ _____ ____ |
-| \ \ / /_ _/ ___|_ _|___ \ |
-| \ V / _` \___ \ | | __) | |
-| | | (_| |___) || | / __/ |
-| |_|\__,_|____/ |_| |_____| |
-| |
-| core system |
-| (C) SuSE GmbH |
-\----------------------------------------------------------------------/
-
- File: PkgModuleFunctionsSource.cc
-
- Author: Klaus Kaempf <kkaempf(a)suse.de>
- Maintainer: Klaus Kaempf <kkaempf(a)suse.de>
-
- Summary: Access to Installation Sources
- Namespace: Pkg
- Purpose: Access to InstSrc
- Handles source related Pkg::function (list_of_arguments) calls
- from WFMInterpreter.
-/-*/
-//#include <unistd.h>
-//#include <sys/statvfs.h>
-
-#include <iostream>
-
-#include <ycpTools.h>
-#include <PkgModule.h>
-#include <PkgModuleFunctions.h>
-
-#include <Callbacks.h>
-#include <Callbacks.YCP.h>
-
-#include <zypp/Product.h>
-#include <zypp/media/MediaManager.h>
-#include <zypp/media/Mount.h>
-#include <zypp/Pathname.h>
-
-#include <zypp/RepoInfo.h>
-#include <zypp/RepoManager.h>
-#include <zypp/Fetcher.h>
-#include <zypp/repo/RepoType.h>
-#include <zypp/MediaProducts.h>
-#include <zypp/ExternalProgram.h>
-#include <zypp/ProgressData.h>
-
-#include <sstream> // ostringstream
-
-#include <PkgProgress.h>
-
-/*
- Textdomain "pkg-bindings"
-*/
-
-// scanned available products
-// hack: zypp/MediaProducts.h cannot be included in PkgModuleFunctions.h
-zypp::MediaProductSet available_products;
-
-// this method should be used instead of zypp::productsInMedia()
-// it initializes the download callbacks
-void PkgModuleFunctions::ScanProductsWithCallBacks(const zypp::Url &url)
-{
- CallInitDownload(std::string(_("Scanning products in ") + url.asString()));
-
- extern ZyppRecipients::MediaChangeSensitivity _silent_probing;
- // remember the current value
- ZyppRecipients::MediaChangeSensitivity _silent_probing_old = _silent_probing;
-
- // disable media change callback for optional file
- _silent_probing = ZyppRecipients::MEDIA_CHANGE_DISABLE;
-
- y2milestone("Scanning products in %s ...", url.asString().c_str());
-
- try
- {
- available_products.clear();
- zypp::productsInMedia(url, available_products);
- }
- catch(...)
- {
- // call the final event even in case of exception
- CallDestDownload();
-
- // restore the probing flag
- _silent_probing = _silent_probing_old;
-
- // rethrow the execption
- throw;
- }
-
- CallDestDownload();
-
- // restore the probing flag
- _silent_probing = _silent_probing_old;
-}
-
-void PkgModuleFunctions::CallSourceReportStart(const std::string &text)
-{
- // get the YCP callback handler
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_SourceReportStart);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- // add parameters
- ycp_handler->appendParameter( YCPInteger(0LL) );
- ycp_handler->appendParameter( YCPString("") );
- ycp_handler->appendParameter( YCPString(text) );
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-
-void PkgModuleFunctions::CallSourceReportEnd(const std::string &text)
-{
- // get the YCP callback handler for end event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_SourceReportEnd);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- // add parameters
- ycp_handler->appendParameter( YCPInteger(0LL) );
- ycp_handler->appendParameter( YCPString("") );
- ycp_handler->appendParameter( YCPString(text) );
- ycp_handler->appendParameter( YCPString("NO_ERROR") );
- ycp_handler->appendParameter( YCPString("") );
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-
-void PkgModuleFunctions::CallSourceReportInit()
-{
- // get the YCP callback handler for init event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_SourceReportInit);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-
-void PkgModuleFunctions::CallSourceReportDestroy()
-{
- // get the YCP callback handler for destroy event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_SourceReportDestroy);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-
-void PkgModuleFunctions::CallInitDownload(const std::string &task)
-{
- // get the YCP callback handler for destroy event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_InitDownload);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- ycp_handler->appendParameter(YCPString(task));
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-
-void PkgModuleFunctions::CallDestDownload()
-{
- // get the YCP callback handler for destroy event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_DestDownload);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-
-// this method should be used instead of RepoManager::refreshMetadata()
-void PkgModuleFunctions::RefreshWithCallbacks(const zypp::RepoInfo &repo)
-{
- CallInitDownload(std::string(_("Refreshing repository ") + repo.alias()));
-
- try
- {
- zypp::RepoManager repomanager = CreateRepoManager();
- repomanager.refreshMetadata(repo);
- }
- catch(...)
- {
- // call the final event even in case of exception
- CallDestDownload();
- // rethrow the execption
- throw;
- }
-
- CallDestDownload();
-}
-
-// this method should be used instead of RepoManager::probe()
-zypp::repo::RepoType PkgModuleFunctions::ProbeWithCallbacks(const zypp::Url &url)
-{
- CallInitDownload(std::string(_("Probing repository ") + url.asString()));
-
- zypp::repo::RepoType repotype;
-
- extern ZyppRecipients::MediaChangeSensitivity _silent_probing;
- // remember the current value
- ZyppRecipients::MediaChangeSensitivity _silent_probing_old = _silent_probing;
-
- // disable media change callback for optional file
- _silent_probing = ZyppRecipients::MEDIA_CHANGE_DISABLE;
-
- try
- {
- // probe type of the repository
- zypp::RepoManager repomanager = CreateRepoManager();
- repotype = repomanager.probe(url);
- }
- catch(...)
- {
- // call the final event even in case of exception
- CallDestDownload();
-
- // restore the probing flag
- _silent_probing = _silent_probing_old;
-
- // rethrow the execption
- throw;
- }
-
- CallDestDownload();
-
- // restore the probing flag
- _silent_probing = _silent_probing_old;
-
- return repotype;
-}
-
-/**
- * Logging helper:
- * call zypp::SourceManager::sourceManager()->findSource
- * and in case of exception, log error and setLastError AND RETHROW
- */
-YRepo_Ptr PkgModuleFunctions::logFindRepository(std::vector<YRepo_Ptr>::size_type id)
-{
- try
- {
- if (id < 0 || id >= repos.size())
- {
- // not found
- throw(std::exception());
- }
-
- if (!repos[id])
- {
- // not found
- throw(std::exception());
- }
-
- if (repos[id]->isDeleted())
- {
- y2error("Source %zd has been deleted, the ID is not valid", id);
- return YRepo_Ptr();
- }
-
- return repos[id];
- }
- catch (...)
- {
- y2error("Cannot find source with ID: %zd", id);
- // TODO: improve the error message
- _last_error.setLastError(_("Cannot find source"));
- }
-
- // not found, return empty pointer
- return YRepo_Ptr();
-}
-
-long long PkgModuleFunctions::logFindAlias(const std::string &alias) const
-{
- std::vector<YRepo_Ptr>::size_type index = 0;
-
- for(std::vector<YRepo_Ptr>::const_iterator it = repos.begin(); it != repos.end() ; ++it, ++index)
- {
- if (!(*it)->isDeleted() && (*it)->repoInfo().alias() == alias)
- return index;
- }
-
- return -1LL;
-}
-
-bool PkgModuleFunctions::aliasExists(const std::string &alias) const
-{
- for(std::vector<YRepo_Ptr>::const_iterator it = repos.begin(); it != repos.end() ; ++it)
- {
- if (!(*it)->isDeleted() && (*it)->repoInfo().alias() == alias)
- return true;
- }
-
- return false;
-}
-
-/****************************************************************************************
- * @builtin SourceSetRamCache
- * @short Obsoleted function, do not use
- * @param boolean
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceSetRamCache (const YCPBoolean& a)
-{
- y2warning( "Pkg::SourceSetRamCache is obsolete and does nothing");
- return YCPBoolean( true );
-}
-
-
-/****************************************************************************************
- * @builtin SourceRestore
- *
- * @short Restore the sources from the persistent store
- * @description
- * Make sure the Source Manager is up and knows all available installation sources.
- * It's safe to call this multiple times, and once the installation sources are
- * actually enabled, it's even cheap
- *
- * @return boolean True on success
- **/
-YCPValue
-PkgModuleFunctions::SourceRestore()
-{
- if (repos.size() > 0)
- {
- y2warning("Number of registered repositories: %zd, skipping repository load!", repos.size());
- return YCPBoolean(true);
- }
-
- bool success = true;
-
- try
- {
- zypp::RepoManager repomanager = CreateRepoManager();
- std::list<zypp::RepoInfo> reps = repomanager.knownRepositories();
-
- repos.clear();
- for (std::list<zypp::RepoInfo>::iterator it = reps.begin();
- it != reps.end(); ++it)
- {
- repos.push_back(new YRepo(*it));
- }
- }
- catch (const zypp::Exception& excpt)
- {
- // FIXME: assuming the sources are already initialized
- y2error ("Error in SourceRestore: %s", excpt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- success = false;
- }
-
- return YCPBoolean(success);
-}
-
-/****************************************************************************************
- * @builtin SourceGetBrokenSources
- *
- * @short Return list of broken sources (sources which failed to restore)
- * @description
- * Get list of all sources which could not have been restored.
- * @return list<string> list of aliases (product names or URLs)
- **/
-YCPValue PkgModuleFunctions::SourceGetBrokenSources()
-{
- y2warning("Pkg::SourceGetBrokenSources() is obsoleted, it's not needed anymore.");
- return YCPList();
-}
-
-bool PkgModuleFunctions::SourceLoadReceiver(const zypp::ProgressData &progress)
-{
- y2milestone("Source Load receiver: %lld (%lld%%)", progress.val(), progress.reportValue());
-
- // get the YCP callback handler for destroy event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_ProcessProgress);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- ycp_handler->appendParameter(YCPInteger(progress.reportValue()));
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-
- return true;
-}
-
-/****************************************************************************************
- * @builtin SourceLoad
- *
- * @short Load resolvables from the installation sources
- * @description
- * Refresh the pool - Add/remove resolvables from the enabled/disabled sources.
- * @return boolean True on success
- **/
-YCPValue
-PkgModuleFunctions::SourceLoad()
-{
- std::list<std::string> stages;
- stages.push_back("Refresh Sources");
- stages.push_back("Rebuild Cache");
- stages.push_back("Load Data");
-
- PkgProgress pkgprogress(_callbackHandler);
-
- // 3 steps per repository (download, cache rebuild, load resolvables)
- pkgprogress.Start("Loading the Package Manager...", stages, "help");
-
- YCPValue ret = SourceLoadImpl(pkgprogress);
-
- pkgprogress.Done();
-
- return ret;
-}
-
-
-/****************************************************************************************
- * @builtin SourceLoad
- *
- * @short Load resolvables from the installation sources
- * @description
- * Refresh the pool - Add/remove resolvables from the enabled/disabled sources.
- * @return boolean True on success
- **/
-YCPValue
-PkgModuleFunctions::SourceLoadImpl(PkgProgress &progress)
-{
- bool success = true;
-
- int repos_to_load = 0;
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
- {
- repos_to_load++;
- }
- }
-
- // set max. value (3 steps per repository - refresh, rebuild, load)
- zypp::ProgressData prog_total(repos_to_load * 3);
- prog_total.sendTo(progress.Receiver());
-
- zypp::RepoManager repomanager = CreateRepoManager();
-
- // refresh metadata
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- // load resolvables only from enabled repos which are not deleted
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
- {
- // sub tasks
- zypp::CombinedProgressData refresh_subprogress(prog_total, 1);
-
- if (AnyResolvableFrom((*it)->repoInfo().alias()))
- {
- y2milestone("Resolvables from '%s' are already present, not loading", (*it)->repoInfo().alias().c_str());
- }
- else
- {
- // autorefresh the source
- if ((*it)->repoInfo().autorefresh())
- {
- try
- {
- y2milestone("Autorefreshing source: %s", (*it)->repoInfo().alias().c_str());
- RefreshWithCallbacks((*it)->repoInfo());
-
- zypp::ProgressData prog(1);
- prog.sendTo(refresh_subprogress);
- RefreshWithCallbacks((*it)->repoInfo());
- prog.toMax();
- }
- // NOTE: subtask progresses are reported as done in the descructor
- // no need to handle them in the exception code
- catch (const zypp::Exception& excpt)
- {
- y2error ("Error in SourceLoad: %s", excpt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- success = false;
- }
- }
- }
- }
- }
-
- progress.NextStage();
-
- // rebuild cache
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- // load resolvables only from enabled repos which are not deleted
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
- {
- // sub tasks
- zypp::CombinedProgressData rebuild_subprogress(prog_total, 1);
-
- if (AnyResolvableFrom((*it)->repoInfo().alias()))
- {
- y2milestone("Resolvables from '%s' are already present, not loading", (*it)->repoInfo().alias().c_str());
- }
- else
- {
- // autorefresh the source
- if ((*it)->repoInfo().autorefresh())
- {
- try
- {
- // rebuild cache (the default policy is "if needed")
- y2milestone("Rebuilding cache for '%s'...", (*it)->repoInfo().alias().c_str());
-
- zypp::ProgressData prog(1);
- prog.sendTo(rebuild_subprogress);
- repomanager.buildCache((*it)->repoInfo());
- prog.toMax();
- }
- // NOTE: subtask progresses are reported as done in the descructor
- // no need to handle them in the exception code
- catch (const zypp::Exception& excpt)
- {
- y2error ("Error in SourceLoad: %s", excpt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- success = false;
- }
- }
- }
- }
- }
-
- progress.NextStage();
-
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- // load resolvables only from enabled repos which are not deleted
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
- {
- // sub tasks
- zypp::CombinedProgressData load_subprogress(prog_total, 1);
-
- if (AnyResolvableFrom((*it)->repoInfo().alias()))
- {
- y2milestone("Resolvables from '%s' are already present, not loading", (*it)->repoInfo().alias().c_str());
- }
- else
- {
- zypp::ProgressData prog(1);
- prog.sendTo(load_subprogress);
-
- // load objects
- success = LoadResolvablesFrom((*it)->repoInfo()) && success;
-
- prog.toMax();
- }
- }
- }
-
- // report 100%
- prog_total.toMax();
-
- return YCPBoolean(success);
-}
-
-
-/****************************************************************************************
- * @builtin SourceStartManager
- *
- * @short Start the source manager - restore the sources and load the resolvables
- * @description
- * Calls SourceRestore(), if argument enable is true SourceLoad() is called.
- * @param boolean enable If true the resolvables are loaded from the enabled sources
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceStartManager (const YCPBoolean& enable)
-{
- PkgProgress pkgprogress(_callbackHandler);
-
- // display the progress only when 'enable' is true
- if (enable->value())
- {
- std::list<std::string> stages;
- stages.push_back("Load Sources");
- stages.push_back("Refresh Sources");
- stages.push_back("Rebuild Cache");
- stages.push_back("Load Data");
-
- // 3 steps per repository (download, cache rebuild, load resolvables)
- pkgprogress.Start("Loading the Package Manager...", stages, "help");
- }
-
- YCPValue ret = SourceStartManagerImpl(enable, pkgprogress);
-
- if (enable->value())
- {
- pkgprogress.Done();
- }
-
- return ret;
-}
-
-/****************************************************************************************
- * @builtin SourceStartManager
- *
- * @short Start the source manager - restore the sources and load the resolvables
- * @description
- * Calls SourceRestore(), if argument enable is true SourceLoad() is called.
- * @param boolean enable If true the resolvables are loaded from the enabled sources
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceStartManagerImpl(const YCPBoolean& enable, PkgProgress &progress)
-{
- YCPValue success = SourceRestore();
-
- progress.NextStage();
-
- if( enable->value() )
- {
- if (!success->asBoolean()->value())
- {
- y2warning("SourceStartManager: Some sources have not been restored, loading only the active sources...");
- }
-
- // enable all sources and load the resolvables
- success = YCPBoolean(SourceLoadImpl(progress)->asBoolean()->value() && success->asBoolean()->value());
- }
-
- return success;
-}
-
-/****************************************************************************************
- * @builtin SourceStartCache
- *
- * @short Make sure the InstSrcManager is up, and return the list of SrcIds.
- * @description
- * Make sure the InstSrcManager is up, and return the list of SrcIds.
- * In fact nothing more than:
- *
- * <code>
- * SourceStartManager( enabled_only );
- * return SourceGetCurrent( enabled_only );
- * </code>
- *
- * @param boolean enabled_only If true, make sure all InstSrces are enabled according to
- * their default, and return the Ids of enabled InstSrces only. If false, return
- * the Ids of all known InstSrces.
- *
- * @return list<integer> list of SrcIds
- **/
-YCPValue
-PkgModuleFunctions::SourceStartCache (const YCPBoolean& enabled)
-{
- try
- {
- SourceStartManager(enabled);
-
- return SourceGetCurrent(enabled);
- }
- catch (const zypp::Exception& excpt)
- {
- y2error ("Error in SourceStartCache: %s", excpt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- }
- // catch an exception from boost (e.g. a file cannot be read by non-root user)
- catch (const std::exception& err)
- {
- y2error ("Error in SourceStartCache: %s", err.what());
- _last_error.setLastError(err.what());
- }
- catch (...)
- {
- y2error("Unknown error in SourceStartCache");
- }
-
- return YCPList();
-}
-
-/****************************************************************************************
- * @builtin SourceCleanupBroken
- *
- * @short Clean up all sources that were not properly restored on the last
- * call of SourceStartManager or SourceStartCache.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceCleanupBroken ()
-{
- y2warning("Pkg::SourceCleanupBroken() is obsoleted, it's not needed anymore.");
- return YCPBoolean(true);
-}
-
-/****************************************************************************************
- * @builtin SourceGetCurrent
- *
- * @short Return the list of all InstSrc Ids.
- *
- * @param boolean enabled_only If true, or omitted, return the Ids of all enabled InstSrces.
- * If false, return the Ids of all known InstSrces.
- *
- * @return list<integer> list of SrcIds (integer)
- **/
-YCPValue
-PkgModuleFunctions::SourceGetCurrent (const YCPBoolean& enabled)
-{
- YCPList res;
-
- std::vector<YRepo_Ptr>::size_type index = 0;
- for( std::vector<YRepo_Ptr>::const_iterator it = repos.begin(); it != repos.end() ; ++it, ++index )
- {
- // ignore disabled sources if requested
- if (enabled->value())
- {
- // Note: enabled() is tribool!
- if ((*it)->repoInfo().enabled())
- {
- }
- else if (!(*it)->repoInfo().enabled())
- {
- continue;
- }
- else
- {
- continue;
- }
- }
-
- // ignore deleted sources
- if ((*it)->isDeleted())
- {
- continue;
- }
-
- res->add( YCPInteger(index) );
- }
-
- return res;
-}
-
-/****************************************************************************************
- * @builtin SourceReleaseAll
- *
- * @short Release all medias hold by all sources
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceReleaseAll ()
-{
- y2milestone("Releasing all sources...");
- bool ret = true;
-
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- try
- {
- (*it)->mediaAccess()->release();
- }
- catch (const zypp::media::MediaException & ex)
- {
- y2warning("Failed to release media for repo: %s", ex.msg().c_str());
- ret = false;
- }
- }
-
- return YCPBoolean(ret);
-}
-
-/******************************************************************************
- * @builtin SourceSaveAll
- *
- * @short Save all InstSrces.
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceSaveAll ()
-{
- y2milestone("Saving the source setup...");
-
- zypp::RepoManager repomanager = CreateRepoManager();
-
- // remove deleted repos (the old configurations) at first
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- // the repo has been removed
- if ((*it)->isDeleted())
- {
- std::string repo_alias = (*it)->repoInfo().alias();
-
- try
- {
- // remove the metadata
- zypp::RepoStatus raw_metadata_status = repomanager.metadataStatus((*it)->repoInfo());
- if (!raw_metadata_status.empty())
- {
- y2milestone("Removing metadata for source '%s'...", repo_alias.c_str());
- repomanager.cleanMetadata((*it)->repoInfo());
- }
-
- // remove the cache
- if (repomanager.isCached((*it)->repoInfo()))
- {
- y2milestone("Removing cache for '%s'...", repo_alias.c_str());
- repomanager.cleanCache((*it)->repoInfo());
- }
-
- repomanager.getRepositoryInfo(repo_alias);
- y2milestone("Removing repository '%s'", repo_alias.c_str());
- repomanager.removeRepository((*it)->repoInfo());
- }
- catch (const zypp::repo::RepoNotFoundException &ex)
- {
- // repository not found -- not critical, continue
- y2warning("No such repository: %s", repo_alias.c_str());
- }
- catch (const zypp::Exception & excpt)
- {
- y2error("Pkg::SourceSaveAll has failed: %s", excpt.msg().c_str() );
- _last_error.setLastError(ExceptionAsString(excpt));
- return YCPBoolean(false);
- }
- }
- }
-
- // save all repos (the current configuration)
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- if (!(*it)->isDeleted())
- {
- std::string current_alias = (*it)->repoInfo().alias();
-
- try
- {
- try
- {
- // if the repository already exists then just modify it
- repomanager.getRepositoryInfo(current_alias);
- y2milestone("Modifying repository '%s'", current_alias.c_str());
- repomanager.modifyRepository(current_alias, (*it)->repoInfo());
- }
- catch (const zypp::repo::RepoNotFoundException &ex)
- {
- // the repository was not found, add it
- y2milestone("Adding repository '%s'", current_alias.c_str());
- repomanager.addRepository((*it)->repoInfo());
- }
- }
- catch (zypp::Exception & excpt)
- {
- y2error("Pkg::SourceSaveAll has failed: %s", excpt.msg().c_str() );
- _last_error.setLastError(ExceptionAsString(excpt));
- return YCPBoolean(false);
- }
- }
- }
-
- y2milestone("All sources have been saved");
-
- return YCPBoolean(true);
-}
-
-/****************************************************************************************
- * @builtin SourceFinishAll
- *
- * @short Save and then disable all InstSrces.
- * @description
- * If there are no enabled sources, do nothing
- * (idempotence hack, broken design: #155459, #176013, use SourceSaveAll).
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceFinishAll ()
-{
- try
- {
- bool found_enabled = false;
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
- {
- found_enabled = true;
- break;
- }
- }
-
- if (!found_enabled)
- {
- y2milestone( "No enabled sources, skipping SourceFinishAll()" );
- return YCPBoolean( true );
- }
-
- SourceSaveAll();
-
- y2milestone( "Disabling all sources...") ;
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- (*it)->repoInfo().setEnabled(false);
- }
- // TODO FIXME remove all resolvables??
- }
- catch (zypp::Exception & excpt)
- {
- y2error("Pkg::SourceFinishAll has failed: %s", excpt.msg().c_str() );
- _last_error.setLastError(ExceptionAsString(excpt));
- return YCPBoolean(false);
- }
-
- y2milestone("All sources have been saved and disabled");
-
- return YCPBoolean(true);
-}
-
-/////////////////////////////////////////////////////////////////////////////////////////
-// Query individual sources
-/////////////////////////////////////////////////////////////////////////////////////////
-
-/****************************************************************************************
- * @builtin SourceGeneralData
- *
- * @short Get general data about the source
- * @description
- * Return general data about the source as a map:
- *
- * <code>
- * $[
- * "enabled" : YCPBoolean,
- * "autorefresh": YCPBoolean,
- * "product_dir": YCPString,
- * "type" : YCPString,
- * "url" : YCPString (without password, but see SourceURL),
- * "alias" : YCPString,
- * "name" : YCPString,
- * ];
- *
- * </code>
- * @param integer SrcId Specifies the InstSrc to query.
- * @return map
- **/
-YCPValue
-PkgModuleFunctions::SourceGeneralData (const YCPInteger& id)
-{
- YCPMap data;
-
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPVoid ();
-
- // convert type to the old strings ("YaST", "YUM" or "Plaindir")
- std::string srctype = zypp2yastType(repo->repoInfo().type().asString());
-
- data->add( YCPString("enabled"), YCPBoolean(repo->repoInfo().enabled()));
- data->add( YCPString("autorefresh"), YCPBoolean(repo->repoInfo().autorefresh()));
- data->add( YCPString("type"), YCPString(srctype));
- data->add( YCPString("product_dir"), YCPString(repo->repoInfo().path().asString()));
-
- // check if there is an URL
- if (repo->repoInfo().baseUrlsBegin() != repo->repoInfo().baseUrlsEnd())
- {
- data->add( YCPString("url"), YCPString(repo->repoInfo().baseUrlsBegin()->asString()));
- }
-
- data->add( YCPString("alias"), YCPString(repo->repoInfo().alias()));
- data->add( YCPString("name"), YCPString(repo->repoInfo().name()));
-
- YCPList base_urls;
- for( zypp::RepoInfo::urls_const_iterator it = repo->repoInfo().baseUrlsBegin(); it != repo->repoInfo().baseUrlsEnd(); ++it)
- {
- base_urls->add(YCPString(it->asString()));
- }
- data->add( YCPString("base_urls"), base_urls);
-
- data->add( YCPString("mirror_list"), YCPString(repo->repoInfo().mirrorListUrl().asString()));
-
- return data;
-}
-
-/******************************************************************************
- * @builtin SourceURL
- *
- * @short Get full source URL, including password
- * @param integer SrcId Specifies the InstSrc to query.
- * @return string or nil on failure
- **/
-YCPValue
-PkgModuleFunctions::SourceURL (const YCPInteger& id)
-{
-
- const YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPVoid();
-
- std::string url;
-
- if (repo->repoInfo().baseUrlsBegin() != repo->repoInfo().baseUrlsEnd())
- {
- // #186842
- url = repo->repoInfo().baseUrlsBegin()->asCompleteString();
- }
-
- return YCPString(url);
-}
-
-/****************************************************************************************
- * @builtin SourceMediaData
- * @short Return media data about the source
- * @description
- * Return media data about the source as a map:
- *
- * <code>
- * $["media_count": YCPInteger,
- * "media_id" : YCPString,
- * "media_vendor" : YCPString,
- * "url" : YCPString,
- * ];
- * </code>
- *
- * @param integer SrcId Specifies the InstSrc to query.
- * @return map
- **/
-YCPValue
-PkgModuleFunctions::SourceMediaData (const YCPInteger& id)
-{
- YCPMap data;
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPVoid ();
-
- std::string alias = repo->repoInfo().alias();
- bool found_resolvable = false;
- int max_medium = 1;
-
- for (zypp::ResPool::const_iterator it = zypp_ptr()->pool().begin()
- ; it != zypp_ptr()->pool().end()
- ; ++it)
- {
- if (it->resolvable()->repository().info().alias() == alias)
- {
- int medium = it->resolvable()->mediaNr();
-
- if (medium > max_medium)
- {
- max_medium = medium;
- }
- }
- }
-
- if (found_resolvable)
- {
- data->add( YCPString("media_count"), YCPInteger(max_medium));
- }
- else
- {
- y2error("No resolvable from repository '%s' found, cannot get number of media (use Pkg::SourceLoad() to load the resolvables)", alias.c_str());
- }
-
- y2warning("Pkg::SourceMediaData() doesn't return \"media_id\" and \"media_vendor\" values anymore.");
-
- // SourceMediaData returns URLs without password
- if (repo->repoInfo().baseUrlsBegin() != repo->repoInfo().baseUrlsEnd())
- {
- data->add( YCPString("url"), YCPString(repo->repoInfo().baseUrlsBegin()->asString()));
-
- // add all base URLs
- YCPList base_urls;
- for( zypp::RepoInfo::urls_const_iterator it = repo->repoInfo().baseUrlsBegin(); it != repo->repoInfo().baseUrlsEnd(); ++it)
- {
- base_urls->add(YCPString(it->asString()));
- }
- data->add( YCPString("base_urls"), base_urls);
- }
-
- return data;
-}
-
-/****************************************************************************************
- * @builtin SourceProductData
- * @short Return Product data about the source
- * @param integer SrcId Specifies the InstSrc to query.
- * @description
- * Product data about the source as a map:
- *
- * <code>
- * $[
- * "label" : YCPString,
- * "vendor" : YCPString,
- * "productname" : YCPString,
- * "productversion" : YCPString,
- * "relnotesurl" : YCPString,
- * ];
- * </code>
- *
- * @return map
- **/
-YCPValue
-PkgModuleFunctions::SourceProductData (const YCPInteger& src_id)
-{
- YCPMap ret;
-
- try
- {
- // find a product for the given source
- zypp::ResPool::byKind_iterator it = zypp_ptr()->pool().byKindBegin(zypp::ResTraits<zypp::Product>::kind);
-
- for( ; it != zypp_ptr()->pool().byKindEnd(zypp::ResTraits<zypp::Product>::kind) ; ++it)
- {
- zypp::Product::constPtr product = boost::dynamic_pointer_cast<const zypp::Product>( it->resolvable() );
-
- if( logFindAlias(product->repository().info().alias()) == src_id->value() )
- {
- ret->add( YCPString("label"), YCPString( product->summary() ) );
- ret->add( YCPString("vendor"), YCPString( product->vendor() ) );
- ret->add( YCPString("productname"), YCPString( product->name() ) );
- ret->add( YCPString("productversion"), YCPString( product->edition().version() ) );
- ret->add( YCPString("relnotesurl"), YCPString( product->releaseNotesUrl().asString()));
-
- #warning SourceProductData not finished
- /*
- data->add( YCPString("datadir"), YCPString( descr->content_datadir().asString() ) );
- TODO (?): "baseproductname", "baseproductversion", "defaultbase", "architectures",
- "requires", "linguas", "labelmap", "language", "timezone", "descrdir", "datadir"
- */
-
- break;
- }
- }
-
- if( it == zypp_ptr()->pool().byKindEnd(zypp::ResTraits<zypp::Product>::kind) )
- {
- y2error ("Product for source '%lld' not found", src_id->value());
- }
- }
- catch (...)
- {
- }
-
- return ret;
-}
-
-/****************************************************************************************
- * @builtin SourceProduct
- * @short Obsoleted function, do not use, see SourceProductData builtin
- * @deprecated
- * @param integer
- * @return map empty map
- **/
-YCPValue
-PkgModuleFunctions::SourceProduct (const YCPInteger& id)
-{
- /* TODO FIXME */
- y2error("Pkg::SourceProduct() is obsoleted, use Pkg::SourceProductData() instead!");
- return YCPMap();
-}
-
-
-YCPValue PkgModuleFunctions::SourceProvideFileCommon(const YCPInteger &id,
- const YCPInteger &mid,
- const YCPString& f,
- const YCPBoolean & optional)
-{
- CallInitDownload(std::string(_("Downloading ") + f->value()));
-
- bool found = true;
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- found = false;
-
- extern ZyppRecipients::MediaChangeSensitivity _silent_probing;
- // remember the current value
- ZyppRecipients::MediaChangeSensitivity _silent_probing_old = _silent_probing;
-
- // disable media change callback for optional file
- if (optional->value())
- _silent_probing = ZyppRecipients::MEDIA_CHANGE_OPTIONALFILE;
-
- zypp::filesystem::Pathname path; // FIXME use ManagedMedia
- if (found)
- {
- try
- {
- path = repo->mediaAccess()->provideFile(f->value(), mid->value());
- y2milestone("local path: '%s'", path.asString().c_str());
- }
- catch (const zypp::Exception& excpt)
- {
- found = false;
-
- if (!optional->value())
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2milestone("File not found: %s", f->value_cstr());
- }
- }
- }
-
- // set the original probing value
- _silent_probing = _silent_probing_old;
-
- CallDestDownload();
-
- if (found)
- {
- return YCPString(path.asString());
- }
- else
- {
- return YCPVoid();
- }
-}
-
-
-/****************************************************************************************
- * @builtin SourceProvideFile
- *
- * @short Make a file available at the local filesystem
- * @description
- * Let an InstSrc provide some file (make it available at the local filesystem).
- *
- * @param integer SrcId Specifies the InstSrc .
- * @param integer medianr Number of the media the file is located on ('1' for the 1st media).
- * @param string file Filename relative to the media root.
- *
- * @return string local path as string
- **/
-YCPValue
-PkgModuleFunctions::SourceProvideFile (const YCPInteger& id, const YCPInteger& mid, const YCPString& f)
-{
- return SourceProvideFileCommon(id, mid, f, false /*optional*/);
-}
-
-/****************************************************************************************
- * @builtin SourceProvideOptionalFile
- *
- * @short Make an optional file available at the local filesystem
- * @description
- * Let an InstSrc provide some file (make it available at the local filesystem).
- * If the file doesn't exist don't ask user for another medium and return nil
- *
- * @param integer SrcId Specifies the InstSrc .
- * @param integer medianr Number of the media the file is located on ('1' for the 1st media).
- * @param string file Filename relative to the media root.
- *
- * @return string local path as string
- **/
-YCPValue
-PkgModuleFunctions::SourceProvideOptionalFile (const YCPInteger& id, const YCPInteger& mid, const YCPString& f)
-{
- return SourceProvideFileCommon(id, mid, f, true /*optional*/);
-}
-
-/****************************************************************************************
- * @builtin SourceProvideDir
- * @short make a directory available at the local filesystem
- * @description
- * Let an InstSrc provide some directory (make it available at the local filesystem) and
- * all the files within it (non recursive).
- *
- * @param integer SrcId Specifies the InstSrc .
- * @param integer medianr Number of the media the file is located on ('1' for the 1st media).
- * @param string dir Directoryname relative to the media root.
- * @return string local path as string
- */
-YCPValue
-PkgModuleFunctions::SourceProvideDir (const YCPInteger& id, const YCPInteger& mid, const YCPString& d)
-{
- y2warning("Pkg::SourceProvideDir() is obsoleted use Pkg::SourceProvideDirectory() instead");
- // non optional, non recursive
- return SourceProvideDirectory(id, mid, d, false, false);
-}
-
-
-/****************************************************************************************
- * @builtin SourceProvideDirectory
- * @short make a directory available at the local filesystem
- * @description
- * Download a directory from repository (make it available at the local filesystem) and
- * all the files within it.
- *
- * @param integer id repository to use (id)
- * @param integer mid Number of the media where the directory is located on ('1' for the 1st media).
- * @param string d Directory name relative to the media root.
- * @param boolean optional set to true if the directory may not exist (do not report errors)
- * @param boolean recursive set to true to provide all subdirectories recursively
- * @return string local path as string or nil when an error occured
- */
-YCPValue
-PkgModuleFunctions::SourceProvideDirectory(const YCPInteger& id, const YCPInteger& mid, const YCPString& d, const YCPBoolean &optional, const YCPBoolean &recursive)
-{
- CallInitDownload(std::string(_("Downloading ") + d->value()));
-
- bool found = true;
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- found = false;
-
- zypp::filesystem::Pathname path; // FIXME user ManagedMedia
-
- extern ZyppRecipients::MediaChangeSensitivity _silent_probing;
- // remember the current value
- ZyppRecipients::MediaChangeSensitivity _silent_probing_old = _silent_probing;
-
- // disable media change callback for optional file
- if (optional->value())
- _silent_probing = ZyppRecipients::MEDIA_CHANGE_OPTIONALFILE;
-
- if (found)
- {
- try
- {
- path = repo->mediaAccess()->provideDir(d->value(), recursive->value(), mid->value());
- }
- catch (const zypp::Exception& excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2milestone ("Directory not found: %s", d->value_cstr());
- found = false;
- }
- }
-
- // set the original probing value
- _silent_probing = _silent_probing_old;
-
- CallDestDownload();
-
- if (found)
- {
- return YCPString(path.asString());
- }
- else
- {
- return YCPVoid();
- }
-}
-
-/****************************************************************************************
- * @builtin SourceChangeUrl
- * @short Change Source URL
- * @description
- * Change url of an InstSrc. Used primarely when re-starting during installation
- * and a cd-device changed from hdX to srX since ide-scsi was activated.
- * @param integer SrcId Specifies the InstSrc.
- * @param string url The new url to use.
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceChangeUrl (const YCPInteger& id, const YCPString& u)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- try
- {
- if (repo->repoInfo().baseUrlsSize() > 1)
- {
- // store current urls
- std::set<zypp::Url> baseUrls (repo->repoInfo().baseUrlsBegin(), repo->repoInfo().baseUrlsEnd());
-
- // reset url list and store the new one there
- repo->repoInfo().setBaseUrl(zypp::Url(u->value()));
-
- // add the rest of base urls
- for (std::set<zypp::Url>::const_iterator i = baseUrls.begin();
- i != baseUrls.end(); ++i)
- repo->repoInfo().addBaseUrl(*i);
- }
- else
- repo->repoInfo().setBaseUrl(zypp::Url(u->value()));
- }
- catch (const zypp::Exception & excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error ("Cannot set the new URL for source %s (%lld): %s",
- repo->repoInfo().alias().c_str(), id->asInteger()->value(), excpt.msg().c_str());
- return YCPBoolean(false);
- }
-
- return YCPBoolean(true);
-}
-
-/****************************************************************************************
- * @builtin SourceInstallOrder
- *
- * @short not implemented, do not use (Explicitly set an install order.)
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceInstallOrder (const YCPMap& ord)
-{
- /* TODO FIXME
- YCPList args;
- args->add (ord);
-
- //-------------------------------------------------------------------------------------//
- YcpArgLoad decl(__FUNCTION__);
-
- YCPMap & order_map( decl.arg<YT_MAP, YCPMap>() );
-
- if ( ! decl.load( args ) ) {
- return pkgError_bad_args;
- }
- //-------------------------------------------------------------------------------------//
-
- InstSrcManager::InstOrder order;
- order.reserve( order_map->size() );
- bool error = false;
-
- for ( YCPMapIterator it = order_map->begin(); it != order_map->end(); ++it ) {
-
- if ( it.value()->isInteger() ) {
- InstSrc::UniqueID uId( it.value()->asInteger()->value() );
- InstSrcManager::ISrcId source_id( _y2pm.instSrcManager().getSourceByID( uId ) );
- if ( source_id ) {
- if ( source_id->enabled() ) {
- order.push_back( uId ); // finaly ;)
-
- } else {
- y2error ("order map entry '%s:%s': source not enabled",
- it.key()->toString().c_str(),
- it.value()->toString().c_str() );
- error = true;
- }
- } else {
- y2error ("order map entry '%s:%s': bad source id",
- it.key()->toString().c_str(),
- it.value()->toString().c_str() );
- error = true;
- }
- } else {
- y2error ("order map entry '%s:%s': integer value expected",
- it.key()->toString().c_str(),
- it.value()->toString().c_str() );
- error = true;
- }
- }
- if ( error ) {
- return pkgError( Error::E_bad_args );
- }
-
- // store new instorder
- _y2pm.instSrcManager().setInstOrder( order );
-*/
-
-#warning SourceInstallOrder is not implemented
- return YCPBoolean( true );
-}
-
-
-static std::string timestamp ()
-{
- time_t t = time(NULL);
- struct tm * tmp = localtime(&t);
-
- if (tmp == NULL) {
- return "";
- }
-
- char outstr[50];
- if (strftime(outstr, sizeof(outstr), "%Y%m%d-%H%M%S", tmp) == 0) {
- return "";
- }
- return outstr;
-}
-
-/**
- * Take the ?alias=foo part of old_url, if any, and return it,
- * putting the rest to new_url.
- * \throws Exception on malformed URLs I guess
- */
-static std::string removeAlias (const zypp::Url & old_url,
- zypp::Url & new_url)
-{
- std::string alias;
- new_url = old_url;
- zypp::url::ParamMap query = new_url.getQueryStringMap ();
- zypp::url::ParamMap::iterator alias_it = query.find ("alias");
- if (alias_it != query.end ())
- {
- alias = alias_it->second;
- query.erase (alias_it);
- new_url.setQueryStringMap (query);
- }
- return alias;
-}
-
-std::string PkgModuleFunctions::UniqueAlias(const std::string &alias)
-{
- // make a copy
- std::string ret = alias;
-
- unsigned int id = 0;
- while(aliasExists(ret))
- {
- y2milestone("Alias %s already found: %lld", ret.c_str(), logFindAlias(ret));
-
- // the alias already exists - add a counter
- std::ostringstream ostr;
- ostr << alias << "_" << id;
-
- ret = ostr.str();
-
- y2milestone("Using alias %s", ret.c_str());
- ++id;
- }
-
- return ret;
-}
-
-
-/**
- * helper - add "mountoptions=ro" for mountable URL schemes if "mountoptions" option is not empty and
- * "rw" or "ro" option is missing
- */
-zypp::Url addRO(const zypp::Url &url)
-{
- zypp::Url ret(url);
- std::string scheme = zypp::str::toLower(url.getScheme());
-
- if (scheme == "nfs"
- || scheme == "hd"
- || scheme == "smb"
- || scheme == "iso"
- || scheme == "cd"
- || scheme == "dvd"
- )
- {
- const std::string mountoptions = "mountoptions";
- zypp::media::Mount::Options options(url.getQueryParam(mountoptions));
-
- y2debug("Current mountoptions: %s", options.asString().c_str());
-
- // if mountoptions are empty lizypp uses "ro" by default
- // don't override "rw" option from application
- // don't add "ro" if it's already present
- if (!options.empty() && !options.has("rw") && !options.has("ro"))
- {
- options["ro"];
-
- ret.setQueryParam(mountoptions, options.asString());
- y2milestone("Adding read only mount option: '%s' -> '%s'", url.asString().c_str(), ret.asString().c_str());
- }
- }
-
- return ret;
-}
-
-// helper function
-zypp::Url PkgModuleFunctions::shortenUrl(const zypp::Url &url)
-{
- std::string url_path = url.getPathName();
- std::string begin_path;
- std::string end_path;
-
- // try to convert 'http://server/dir1/dir2/dir3/dir4' -> 'http://server/dir1/.../dir4'
- std::string::size_type pos_first = url_path.find("/");
- if (pos_first == 0)
- {
- pos_first = url_path.find("/", 1);
- }
-
- if (pos_first == std::string::npos)
- {
- const int num = 5;
-
- // "/" not found use the beginning and the end part
- // 'http://server/very_long_directory_name' -> 'http://server/very_..._name'
- begin_path = std::string(url_path, 0, num);
- end_path = std::string(url_path, url_path.size() - num - 1, num);
- }
- else
- {
- unsigned int pos_last = url_path.rfind("/");
- if (pos_last == url_path.size() - 1)
- {
- pos_last = url_path.rfind("/", url_path.size() - 1);
- }
-
- if (pos_last == pos_first || pos_last < pos_first)
- {
- const int num = 5;
-
- // "/" not found use the beginning and the end part
- begin_path = std::string(url_path, 0, num);
- end_path = std::string(url_path, url_path.size() - num - 1, num);
- }
- else
- {
- begin_path = std::string(url_path, 0, pos_first + 1);
- end_path = std::string(url_path, pos_last);
- }
- }
-
- std::string new_path = begin_path + "..." + end_path;
- zypp::Url ret(url);
-
- // use the shorter path
- ret.setPathName(new_path);
- // remove query parameters
- ret.setQueryString("");
- // remove fragmet
- ret.setFragment("");
-
- y2milestone("Using shortened URL: '%s' -> '%s'", url.asString().c_str(), ret.asString().c_str());
- return ret;
-}
-
-/** Create a Source and immediately put it into the SourceManager.
- * \return the SourceId
- * \throws Exception if Source creation fails
-*/
-std::vector<zypp::RepoInfo>::size_type
-PkgModuleFunctions::createManagedSource( const zypp::Url & url_r,
- const zypp::Pathname & path_r,
- const bool base_source,
- const std::string& type,
- const std::string &alias_r )
-{
- // parse URL
- y2milestone ("Original URL: %s, product directory: %s", url_r.asString().c_str(), path_r.asString().c_str());
-
- // #158850#c17, if the URL contains an alias, we use that
- zypp::Url url;
-
- std::string alias = removeAlias(url_r, url);
- y2milestone("Alias from URL: '%s'", alias.c_str());
-
-#warning FIXME: use base_source (base_source vs. addon) (will be probably not needed)
-
- // repository type
- zypp::repo::RepoType repotype;
- zypp::RepoManager repomanager = CreateRepoManager();
-
- if (!type.empty())
- {
- try
- {
- // do conversion from the Yast type ("YaST", "YUM", "Plaindir")
- // to libzypp type ("yast", "yum", "plaindir")
- repotype = repotype.parse(yast2zyppType(type));
- }
- catch (zypp::repo::RepoUnknownTypeException &e)
- {
- y2warning("Unknown source type '%s'", type.c_str());
- }
- }
-
- // the type is not specified or is wrong, autoprobe the type
- if (repotype == zypp::repo::RepoType::NONE)
- {
- zypp::Url probe_url(url_r);
-
- if (!path_r.asString().empty())
- {
- zypp::Pathname pth(probe_url.getPathName());
- pth /= path_r;
-
- probe_url.setPathName(pth.asString());
- }
-
- y2milestone("Probing source type: '%s'", probe_url.asString().c_str());
-
- // autoprobe type of the repository
- repotype = ProbeWithCallbacks(probe_url);
- }
-
- y2milestone("Using source type: %s", repotype.asString().c_str());
-
-
- // create source definition object
- zypp::RepoInfo repo;
-
- std::string name;
-
- // set alias and name
- if (alias.empty())
- {
- // alias not set via URL, use the passed alias or the URL path
- if (alias_r.empty())
- {
- // use the last path element in URL
- std::string url_path = url.getPathName();
-
- std::string::size_type pos_begin = url_path.rfind("/");
- std::string::size_type pos_end = std::string::npos;
-
- // ignore the trailing slash
- if (pos_begin == url_path.size() - 1)
- {
- pos_begin = url_path.rfind("/", url_path.size() - 2);
-
- if (pos_begin != std::string::npos)
- {
- pos_end = url_path.size() - pos_begin - 2;
- }
- }
- else
- {
- pos_end = url_path.size() - pos_begin - 1;
- }
-
- // ignore the found slash character
- pos_begin++;
-
- alias = std::string(url_path, pos_begin, pos_end);
-
- y2milestone("Alias from URL path: %s", alias.c_str());
-
- // fallback
- if (alias.empty())
- {
- y2milestone("URL alias is empty using 'Repository'");
- alias = "Repository";
- }
- }
- else
- {
- alias = alias_r;
- }
-
- name = alias;
- }
- else
- {
- name = alias;
- }
-
-
- y2milestone("Name of the repository: '%s'", name.c_str());
-
- // alias must be unique, add a suffix if it's already used
- alias = UniqueAlias(alias);
-
- // add read only mount option to the URL if needed
- url = addRO(url);
-
- bool autorefresh = true;
-
- std::string scheme = zypp::str::toLower(url.getScheme());
- if (scheme == "cd" || scheme == "dvd")
- {
- y2milestone("Disabling autorefresh for CD/DVD repository");
- autorefresh = false;
- }
-
- repo.setAlias(alias);
- repo.setName(name);
- repo.setType(repotype);
- repo.addBaseUrl(url);
- repo.setPath(path_r);
- repo.setEnabled(true);
- repo.setAutorefresh(autorefresh);
-
- // set metadata path (#293428)
- zypp::Pathname metadatapath = repomanager.metadataPath(repo);
- repo.setMetadataPath(metadatapath);
-
- y2milestone("Adding source '%s' (%s, dir: %s)", repo.alias().c_str(), url.asString().c_str(), path_r.asString().c_str());
- // note: exceptions should be caught by the calling code
- RefreshWithCallbacks(repo);
-
- // build cache if needed
- if (!repomanager.isCached(repo))
- {
- y2milestone("Caching source '%s'...", repo.alias().c_str());
- repomanager.buildCache(repo);
- }
-
- repos.push_back(new YRepo(repo));
-
- y2milestone("Added source '%s': '%s', enabled: %s, autorefresh: %s",
- repo.alias().c_str(),
- repo.baseUrlsBegin()->asString().c_str(),
- repo.enabled() ? "true" : "false",
- repo.autorefresh() ? "true" : "false"
- );
-
- // the source is at the end of the list
- return repos.size() - 1;
-}
-
-/****************************************************************************************
- * @builtin RepositoryAdd
- *
- * @short Register a new repository
- * @description
- * Adds a new repository to the internal structures. The repository is only registered,
- * metadata is not downloaded, use Pkg::SourceRefreshNow() for that. The metadata is also loaded
- * automatically when loading the repository content (Pkg::SourceLoad())
- *
- * @param map map with repository parameters: $[ "enabled" : boolean, "autorefresh" : boolean, "name" : string,
- * "alias" : string, "base_urls" : list<string>, "prod_dir" : string, "type" : string ]
- * @return integer Repository ID or nil on error
- **/
-YCPValue PkgModuleFunctions::RepositoryAdd(const YCPMap ¶ms)
-{
- zypp::RepoInfo repo;
-
- // turn on the repo by default
- repo.setEnabled(true);
- // enable autorefresh by default
- repo.setAutorefresh(true);
-
- if (!params->value( YCPString("enabled") ).isNull() && params->value(YCPString("enabled"))->isBoolean())
- {
- repo.setEnabled(params->value(YCPString("enabled"))->asBoolean()->value());
- }
-
- if (!params->value( YCPString("autorefresh") ).isNull() && params->value(YCPString("autorefresh"))->isBoolean())
- {
- repo.setAutorefresh(params->value(YCPString("autorefresh"))->asBoolean()->value());
- }
-
- std::string alias;
-
- if (!params->value( YCPString("alias") ).isNull() && params->value(YCPString("alias"))->isString())
- {
- alias = params->value(YCPString("alias"))->asString()->value();
- }
-
- if (alias.empty())
- {
- alias = timestamp();
-
- // the alias must be unique
- alias = UniqueAlias(alias);
- }
- else
- {
- if (aliasExists(alias))
- {
- ycperror("alias %s already exists", alias.c_str());
- return YCPVoid();
- }
- }
-
- repo.setAlias(alias);
-
- // use the first base URL as a fallback name
- std::string first_url;
-
- if (!params->value( YCPString("base_urls") ).isNull() && params->value(YCPString("base_urls"))->isList())
- {
- YCPList lst(params->value(YCPString("base_urls"))->asList());
-
- for (int index = 0; index < lst->size(); ++index)
- {
- if( ! lst->value(index)->isString() )
- {
- ycperror( "Pkg::RepositoryAdd(): entry not a string at index %d: %s", index, lst->toString().c_str());
- return YCPVoid();
- }
-
- zypp::Url url;
-
- try
- {
- url = lst->value(index)->asString()->value();
- zypp::Url url_new;
-
- std::string name = removeAlias(url, url_new);
-
- if (!name.empty())
- {
- repo.setName(name);
- url = url_new;
- }
-
- // add read only mount option to the URL if needed
- url = addRO(url);
- }
- catch(const zypp::Exception & expt)
- {
- y2error("Invalid URL: %s", expt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(expt));
- return YCPVoid();
- }
-
- if (index == 0)
- {
- first_url = url.asString();
- }
-
- repo.addBaseUrl(url);
- }
- }
- else
- {
- ycperror("Missing \"base_urls\" key in the map");
- return YCPVoid();
- }
-
- // check name parameter
- if (!params->value( YCPString("name") ).isNull() && params->value(YCPString("name"))->isString())
- {
- repo.setName(params->value(YCPString("name"))->asString()->value());
- }
- else
- {
- // if the key "name" is missing and the name hasn't been set by ?alias= in the URL
- // then use the first URL as the name
- if (repo.name().empty())
- {
- repo.setName(first_url);
- }
- }
-
- if (!params->value( YCPString("type") ).isNull() && params->value(YCPString("type"))->isString())
- {
- std::string type = yast2zyppType(params->value(YCPString("type"))->asString()->value());
-
- try
- {
- zypp::repo::RepoType repotype(type);
- repo.setType(repotype);
- }
- catch (zypp::repo::RepoUnknownTypeException &e)
- {
- ycperror("Unknown source type '%s': %s", type.c_str(), e.asString().c_str());
- _last_error.setLastError(ExceptionAsString(e));
- return YCPVoid();
- }
-
- }
-
- if (!params->value( YCPString("prod_dir") ).isNull() && params->value(YCPString("prod_dir"))->isString())
- {
- repo.setPath(params->value(YCPString("prod_dir"))->asString()->value());
- }
-
- // set metadata path (#293428)
- zypp::RepoManager repomanager = CreateRepoManager();
- zypp::Pathname metadatapath = repomanager.metadataPath(repo);
- repo.setMetadataPath(metadatapath);
-
- repos.push_back(new YRepo(repo));
-
- // the new source is at the end of the list
- return YCPInteger(repos.size() - 1);
-}
-
-/****************************************************************************************
- * @builtin SourceCacheCopyTo
- *
- * @short Copy cache data of all installation sources to the target
- * @description
- * Copy cache data of all installation sources to the target located below 'dir'.
- * To be called at end of initial installation.
- *
- * @param string dir Root directory of target.
- * @return boolean true on success
- **/
-YCPValue
-PkgModuleFunctions::SourceCacheCopyTo (const YCPString& dir)
-{
- // error message (followed by detailed description)
- const std::string msg = _("Error: Cannot copy the cache to the target directory\n");
-
- std::string d = dir->value();
- y2milestone("Copying source cache to '%s'...", d.c_str());
-
- if (d.empty())
- {
- y2error("Empty parameter in Pkg::SourceCacheCopyTo()!");
- return YCPBoolean(false);
- }
-
- std::string target = d + "/var/cache";
-
- // create the target dir
- const char* argv[] =
- {
- "mkdir",
- // create parent dir
- "-p",
- // finish parameter list
- "--",
- // target
- target.c_str(),
- NULL
- };
-
- // discard stderr, no pty, stderr_fd = -1, use the default locale
- zypp::ExternalProgram prog(argv, zypp::ExternalProgram::Discard_Stderr, false, -1, true);
-
- int code = prog.close();
-
- if (code)
- {
- // error message (followed by directory name)
- _last_error.setLastError(msg + _("Cannot create directory ") + target);
- y2error("Cannot create target directory %s", target.c_str());
- return YCPBoolean(false);
- }
-
- // copy /var/cache/zypp to the target system
- const char* argv2[] =
- {
- "cp",
- // preserve time stamps
- "-a",
- // recursive
- "-r",
- // finish parameter list
- "--",
- // source
- "/var/cache/zypp",
- // target
- target.c_str(),
- NULL
- };
-
- // discard stderr, no pty, stderr_fd = -1, use the default locale
- zypp::ExternalProgram prog2(argv2, zypp::ExternalProgram::Discard_Stderr, false, -1, true);
-
- int code2 = prog2.close();
-
- if (code2)
- {
- // error message
- _last_error.setLastError(msg + _("Copying failed"));
- y2error("Cannot copy /var/cache/zypp to %s", d.c_str());
- }
-
- return YCPBoolean(!code2);
-}
-
-/****************************************************************************************
- * @builtin SourceScan
- * @short Scan a Source Media
- * @description
- * Load all InstSrces found at media_url, i.e. all sources mentioned in /media.1/products.
- * If no /media.1/products is available, InstSrc is expected to be located directly
- * below media_url (product_dir: /).
- *
- * If a product_dir is provided, only the InstSrc located at media_url/product_dir is loaded.
- *
- * In contrary to @ref SourceCreate, InstSrces are loaded into the InstSrcManager,
- * but not enabled (packages and selections are not provided to the PackageManager),
- * and the SrcIds of <b>all</b> InstSrces found are returned.
- *
- * @param string url The media to scan.
- * @optarg string product_dir Restrict scan to a certain InstSrc located in media_url/product_dir.
- *
- * @return list<integer> list of SrcIds (integer).
- **/
-YCPValue
-PkgModuleFunctions::SourceScan (const YCPString& media, const YCPString& pd)
-{
- zypp::Url url;
-
- try {
- url = zypp::Url(media->value ());
- }
- catch(const zypp::Exception & expt )
- {
- y2error ("Invalid URL: %s", expt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(expt));
- return YCPList();
- }
-
- zypp::Pathname pn(pd->value ());
-
- YCPList ids;
- std::vector<zypp::RepoInfo>::size_type id;
-
- if ( pd->value().empty() ) {
-
- // scan all sources
- zypp::MediaProductSet products;
-
- try
- {
- y2milestone("Scanning products in %s ...", url.asString().c_str());
- ScanProductsWithCallBacks(url);
- products = available_products;
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("Scanning products for '%s' has failed"
- , url.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- return ids;
- }
-
- if( products.empty() )
- {
- // no products found, use the base URL instead
- zypp::MediaProductEntry entry;
- products.insert(entry);
- }
-
- for( zypp::MediaProductSet::const_iterator it = products.begin();
- it != products.end() ; ++it )
- {
- try
- {
- y2milestone("Using product %s in directory %s", it->_name.c_str(), it->_dir.c_str());
- id = createManagedSource(url, it->_dir, false, "", it->_name);
- ids->add( YCPInteger(id) );
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("SourceScan for '%s' product '%s' has failed"
- , url.asString().c_str(), pn.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- }
- }
- } else {
- y2debug("Creating source...");
-
- try
- {
- id = createManagedSource(url, pn, false, "", "");
- ids->add( YCPInteger(id) );
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("SourceScan for '%s' product '%s' has failed"
- , url.asString().c_str(), pn.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- }
- }
-
- y2milestone("Found sources: %s", ids->toString().c_str() );
-
- return ids;
-}
-
-/****************************************************************************************
- * @builtin SourceCreate
- *
- * @short Create a Source
- * @description
- * Load and enable all InstSrces found at media_url, i.e. all sources mentioned in /media.1/products.
- * If no /media.1/products is available, InstSrc is expected to be located directly below
- * media_url (product_dir: /).
- *
- * If a product_dir is provided, only the InstSrc located at media_url/product_dir is loaded
- * and enabled.
- *
- * @param string url The media to scan.
- * @optarg string product_dir Restrict scan to a certain InstSrc located in media_url/product_dir.
- *
- * @return integer The source_id of the first InstSrc found on the media.
- **/
-YCPValue
-PkgModuleFunctions::SourceCreate (const YCPString& media, const YCPString& pd)
-{
- // not base product, autoprobe source type
- return SourceCreateEx (media, pd, false, YCPString(""));
-}
-
-YCPValue
-PkgModuleFunctions::SourceCreateBase (const YCPString& media, const YCPString& pd)
-{
- // base product, autoprobe source type
- return SourceCreateEx (media, pd, true, YCPString(""));
-}
-
-/**
- * @builtin SourceCreateType
- * @short Create source of required type
- * @description
- * Create a source without autoprobing the source type. This builtin should be used only for "Plaindir" sources, because Plaindir sources are not automatically probed in SourceCreate() builtin.
- * @param media URL of the source
- * @param pd product directory (if empty the products will be searched)
- * @param type type of the source ("YaST", "YUM" or "Plaindir")
-*/
-
-YCPValue
-PkgModuleFunctions::SourceCreateType (const YCPString& media, const YCPString& pd, const YCPString& type)
-{
- // not base product, autoprobe source type
- return SourceCreateEx (media, pd, false, type);
-}
-
-YCPValue
-PkgModuleFunctions::SourceCreateEx (const YCPString& media, const YCPString& pd, bool base, const YCPString& source_type)
-{
- y2debug("Creating source...");
-
- zypp::Pathname pn(pd->value ());
-
- zypp::Url url;
-
- try {
- url = zypp::Url(media->value ());
- }
- catch(const zypp::Exception & expt )
- {
- y2error ("Invalid URL: %s", expt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(expt));
- return YCPInteger (-1LL);
- }
-
-
- YCPList ids;
- std::vector<zypp::RepoInfo>::size_type ret = -1;
-
- const std::string type = source_type->value();
-
- if ( pd->value().empty() ) {
- // scan all sources
- zypp::MediaProductSet products;
-
- try {
- ScanProductsWithCallBacks(url);
- products = available_products;
- }
- catch ( const zypp::Exception& excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error( "Cannot read the product list from the media" );
- return YCPInteger(-1LL);
- }
-
- if( products.empty() )
- {
- // no products found, use the base URL instead
- zypp::MediaProductEntry entry ;
- products.insert( entry );
- }
-
- for( zypp::MediaProductSet::const_iterator it = products.begin();
- it != products.end() ; ++it )
- {
- try
- {
- std::vector<zypp::RepoInfo>::size_type id = createManagedSource(url, it->_dir, base, type, it->_name);
- YRepo_Ptr repo = logFindRepository(id);
-
- LoadResolvablesFrom(repo->repoInfo());
-
- // return the id of the first product
- if ( it == products.begin() )
- ret = id;
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("SourceCreate for '%s' product '%s' has failed"
- , url.asString().c_str(), pn.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- return YCPInteger(-1LL);
- }
- }
- } else {
- y2debug("Creating source...");
-
- try
- {
- ret = createManagedSource(url, pn, base, type, "");
-
- YRepo_Ptr repo = logFindRepository(ret);
- repo->repoInfo().setEnabled(true);
-
- LoadResolvablesFrom(repo->repoInfo());
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("SourceCreate for '%s' product '%s' has failed"
- , url.asString().c_str(), pn.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- }
- }
-
- PkgFreshen();
- return YCPInteger(repos.size() - 1);
-}
-
-
-/****************************************************************************************
- * @builtin SourceSetEnabled
- *
- * @short Set the default activation state of an InsrSrc.
- * @param integer SrcId Specifies the InstSrc.
- * @param boolean enabled Default activation state of source.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceSetEnabled (const YCPInteger& id, const YCPBoolean& e)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- // no change required
- bool enable = e->value();
- if ((enable && repo->repoInfo().enabled())
- || (!enable && !repo->repoInfo().enabled()))
- return YCPBoolean(true);
-
- bool success = true;
-
- try
- {
- repo->repoInfo().setEnabled(enable);
-
- // add/remove resolvables
- if (enable)
- {
- // load resolvables only when they are missing
- if (!AnyResolvableFrom(repo->repoInfo().alias()))
- {
- success = LoadResolvablesFrom(repo->repoInfo());
- }
- }
- else
- {
- // the source has been disabled, remove resolvables from the pool
- RemoveResolvablesFrom(repo->repoInfo().alias());
- }
-
- PkgFreshen();
- }
- catch (const zypp::Exception& excpt)
- {
- std::string alias = repo->repoInfo().alias();
- y2error ("Error for '%s': %s", alias.c_str(), excpt.asString().c_str());
- _last_error.setLastError(alias + ": " + ExceptionAsString(excpt));
- success = false;
- }
-
- return YCPBoolean(success);
-}
-
-/****************************************************************************************
- * @builtin SourceSetAutorefresh
- *
- * @short Set whether this source should automaticaly refresh it's
- * meta data when it gets enabled. (default true, if not CD/DVD)
- * @param integer SrcId Specifies the InstSrc.
- * @param boolean enabled Whether autorefresh should be turned on or off.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceSetAutorefresh (const YCPInteger& id, const YCPBoolean& e)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- repo->repoInfo().setAutorefresh(e->value());
-
- return YCPBoolean( true );
-}
-
-/****************************************************************************************
- * @builtin SourceFinish
- * @short Disable an Installation Source
- * @param integer SrcId Specifies the InstSrc.
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceFinish (const YCPInteger& id)
-{
- return SourceSetEnabled(id, false);
-}
-
-/****************************************************************************************
- * @builtin SourceRefreshNow
- * @short Attempt to immediately refresh a Source
- * @description
- * The InsrSrc will be encouraged to check and refresh all metadata
- * cached on disk.
+/* ------------------------------------------------------------------------------
+ * Copyright (c) 2007 Novell, Inc. All Rights Reserved.
*
- * @param integer SrcId Specifies the InstSrc.
*
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceRefreshNow (const YCPInteger& id)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- try
- {
- zypp::RepoManager repomanager = CreateRepoManager();
- y2milestone("Refreshing metadata '%s'", repo->repoInfo().alias().c_str());
- RefreshWithCallbacks(repo->repoInfo());
-
- y2milestone("Caching source '%s'...", repo->repoInfo().alias().c_str());
- repomanager.buildCache(repo->repoInfo());
- }
- catch ( const zypp::Exception & expt )
- {
- y2error ("Error while refreshing the source: %s", expt.asString().c_str());
- _last_error.setLastError(repo->repoInfo().alias() + ": " + ExceptionAsString(expt));
- return YCPBoolean(false);
- }
-
- return YCPBoolean( true );
-}
-
-/****************************************************************************************
- * @builtin SourceDelete
- * @short Delete a Source
- * @description
- * Delete an InsrSrc. The InsrSrc together with all metadata cached on disk
- * is removed. The SrcId passed becomes invalid (other SrcIds stay valid).
+ * This program is free software; you can redistribute it and/or modify it under
+ * the terms of version 2 of the GNU General Public License as published by the
+ * Free Software Foundation.
*
- * @param integer SrcId Specifies the InstSrc.
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+ * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceDelete (const YCPInteger& id)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- bool success = true;
+ * You should have received a copy of the GNU General Public License along with
+ * this program; if not, contact Novell, Inc.
+ *
+ * To contact Novell about this file by physical or electronic mail, you may find
+ * current contact information at www.novell.com.
+ * ------------------------------------------------------------------------------
+ */
- try
- {
- // the resolvables cannot be used anymore, remove them
- RemoveResolvablesFrom(repo->repoInfo().alias());
+/*
+ File: $Id:$
+ Author: Ladislav Slezák <lslezak(a)novell.com>
+ Summary: Functions used during system installation
+*/
- // update 'repos'
- repo->setDeleted();
+#include <Callbacks.h>
+#include <Callbacks.YCP.h>
- PkgFreshen();
- }
- catch (const zypp::Exception& excpt)
- {
- std::string alias = repo->repoInfo().alias();
- y2error ("Error for '%s': %s", alias.c_str(), excpt.asString().c_str());
- _last_error.setLastError(alias + ": " + ExceptionAsString(excpt));
- success = false;
- }
+#include <PkgModule.h>
+#include <PkgModuleFunctions.h>
- return YCPBoolean(success);
-}
+#include <zypp/ExternalProgram.h>
/****************************************************************************************
- * @builtin SourceEditGet
- *
- * @short Get state of Sources
- * @description
- * Return a list of states for all known InstSources sorted according to the
- * source priority (highest first). A source state is a map:
- * $[
- * "SrcId" : YCPInteger,
- * "enabled" : YCPBoolean
- * "autorefresh": YCPBoolean
- * ];
- *
- * @return list<map> list of source states (map)
+ * @builtin SourceSetRamCache
+ * @short Obsoleted function, do not use
+ * @param boolean
+ * @return boolean
**/
YCPValue
-PkgModuleFunctions::SourceEditGet ()
+PkgModuleFunctions::SourceSetRamCache (const YCPBoolean& a)
{
- YCPList ret;
-
- unsigned long index = 0;
- for( std::vector<YRepo_Ptr>::const_iterator it = repos.begin(); it != repos.end(); ++it, ++index)
- {
- if (!(*it)->isDeleted())
- {
- YCPMap src_map;
-
- src_map->add(YCPString("SrcId"), YCPInteger(index));
- // Note: enabled() is tribool
- src_map->add(YCPString("enabled"), YCPBoolean((*it)->repoInfo().enabled()));
- // Note: autorefresh() is tribool
- src_map->add(YCPString("autorefresh"), YCPBoolean((*it)->repoInfo().autorefresh()));
- src_map->add(YCPString("name"), YCPString((*it)->repoInfo().name()));
+ y2warning( "Pkg::SourceSetRamCache is obsolete and does nothing");
+ return YCPBoolean( true );
+}
- ret->add(src_map);
- }
- }
- return ret;
-}
/****************************************************************************************
- * @builtin SourceEditSet
+ * @builtin SourceCacheCopyTo
*
- * @short Configure properties of installation sources
+ * @short Copy cache data of all installation sources to the target
* @description
- * Set states of installation sources. Note: Enabling/disabling a source does not
- * (un)load the packages from the source! Use SourceSetEnabled() if you need to refresh
- * the packages in the pool.
- *
- * @param list source_states List of source states. Same format as returned by
- * @see SourceEditGet.
+ * Copy cache data of all installation sources to the target located below 'dir'.
+ * To be called at end of initial installation.
*
- * @return boolean
+ * @param string dir Root directory of target.
+ * @return boolean true on success
**/
YCPValue
-PkgModuleFunctions::SourceEditSet (const YCPList& states)
+PkgModuleFunctions::SourceCacheCopyTo (const YCPString& dir)
{
- bool error = false;
-
- for (int index = 0; index < states->size(); index++ )
- {
- if( ! states->value(index)->isMap() )
- {
- ycperror( "Pkg::SourceEditSet, entry not a map at index %d", index);
- error = true;
- continue;
- }
-
- YCPMap descr = states->value(index)->asMap();
-
- if (descr->value( YCPString("SrcId") ).isNull() || !descr->value(YCPString("SrcId"))->isInteger())
- {
- ycperror( "Pkg::SourceEditSet, SrcId not defined for a source description at index %d", index);
- error = true;
- continue;
- }
-
- std::vector<YRepo_Ptr>::size_type id = descr->value( YCPString("SrcId") )->asInteger()->value();
+ // error message (followed by detailed description)
+ const std::string msg = _("Error: Cannot copy the cache to the target directory\n");
- YRepo_Ptr repo = logFindRepository(id);
- if (!repo)
- {
- ycperror( "Pkg::SourceEditSet, source %d not found", index);
- error = true;
- continue;
- }
+ std::string d = dir->value();
+ y2milestone("Copying source cache to '%s'...", d.c_str());
- // now, we have the source
- if( ! descr->value( YCPString("enabled")).isNull() && descr->value(YCPString("enabled"))->isBoolean ())
+ if (d.empty())
{
- bool enable = descr->value(YCPString("enabled"))->asBoolean ()->value();
-
- if (repo->repoInfo().enabled() != enable)
- {
- ycpwarning("Pkg::SourceEditSet() does not refresh the pool (src: %zd, state: %s)", id, enable ? "disabled -> enabled" : "enabled -> disabled");
- }
-
- y2debug("set enabled: %d", enable);
- repo->repoInfo().setEnabled(enable);
+ y2error("Empty parameter in Pkg::SourceCacheCopyTo()!");
+ return YCPBoolean(false);
}
- if( !descr->value(YCPString("autorefresh")).isNull() && descr->value(YCPString("autorefresh"))->isBoolean ())
- {
- bool autorefresh = descr->value(YCPString("autorefresh"))->asBoolean()->value();
- y2debug("set autorefresh: %d", autorefresh);
- repo->repoInfo().setAutorefresh( autorefresh );
- }
+ std::string target = d + "/var/cache";
- if( !descr->value(YCPString("name")).isNull() && descr->value(YCPString("name"))->isString())
+ // create the target dir
+ const char* argv[] =
{
- // rename the source
- y2debug("set name: %s", descr->value(YCPString("name"))->asString()->value().c_str());
- repo->repoInfo().setName(descr->value(YCPString("name"))->asString()->value());
- }
-
-#warning SourceEditSet ordering not implemented yet
- }
-
- PkgFreshen();
- return YCPBoolean( !error );
-}
+ "mkdir",
+ // create parent dir
+ "-p",
+ // finish parameter list
+ "--",
+ // target
+ target.c_str(),
+ NULL
+ };
-/////////////////////////////////////////////////////////////////////////////////////////
-//
-// DEPRECATED
-//
-/////////////////////////////////////////////////////////////////////////////////////////
+ // discard stderr, no pty, stderr_fd = -1, use the default locale
+ zypp::ExternalProgram prog(argv, zypp::ExternalProgram::Discard_Stderr, false, -1, true);
-/****************************************************************************************
- * Pkg::SourceRaisePriority (integer SrcId) -> bool
- *
- * Raise priority of source.
- *
- * @param SrcId Specifies the InstSrc.
- *
- * @return bool
- **/
-YCPValue
-PkgModuleFunctions::SourceRaisePriority (const YCPInteger& id)
-{
-#warning SourceRaisePriority is not implemented
- y2warning("SourceRaisePriority is NOT implemented");
-/* zypp::Source_Ref src;
+ int code = prog.close();
- try {
- src = logFindRepository(id->value());
- }
- catch (const zypp::Exception& excpt)
+ if (code)
{
+ // error message (followed by directory name)
+ _last_error.setLastError(msg + _("Cannot create directory ") + target);
+ y2error("Cannot create target directory %s", target.c_str());
return YCPBoolean(false);
}
- // raise priority by one
- src.setPriority(src.priority() + 1);
-*/
-
- return YCPBoolean( true );
+ // copy /var/cache/zypp to the target system
+ const char* argv2[] =
+ {
+ "cp",
+ // preserve time stamps
+ "-a",
+ // recursive
+ "-r",
+ // finish parameter list
+ "--",
+ // source
+ "/var/cache/zypp",
+ // target
+ target.c_str(),
+ NULL
+ };
-}
+ // discard stderr, no pty, stderr_fd = -1, use the default locale
+ zypp::ExternalProgram prog2(argv2, zypp::ExternalProgram::Discard_Stderr, false, -1, true);
-/****************************************************************************************
- * Pkg::SourceLowerPriority (integer SrcId) -> void
- *
- * Lower priority of source.
- *
- * @param SrcId Specifies the InstSrc.
- *
- * @return bool
- */
-YCPValue
-PkgModuleFunctions::SourceLowerPriority (const YCPInteger& id)
-{
-#warning SourceLowerPriority is not implemented
- y2warning("SourceLowerPriority is NOT implemented");
-/*
- zypp::Source_Ref src;
+ int code2 = prog2.close();
- try {
- src = logFindRepository(id->value());
- }
- catch (const zypp::Exception& excpt)
+ if (code2)
{
- return YCPBoolean(false);
+ // error message
+ _last_error.setLastError(msg + _("Copying failed"));
+ y2error("Cannot copy /var/cache/zypp to %s", d.c_str());
}
- // lower priority by one
- src.setPriority(src.priority() - 1);
-*/
- return YCPBoolean( true );
-}
-
-/****************************************************************************************
- * Pkg::SourceSaveRanks () -> boolean
- *
- * @short Obsoleted function, do not use
- * @return boolean true
- **/
-YCPValue
-PkgModuleFunctions::SourceSaveRanks ()
-{
- y2error( "SourceSaveRanks not implemented" );
-
- return YCPBoolean( true );
+ return YCPBoolean(!code2);
}
-
/****************************************************************************************
* @builtin SourceMoveDownloadArea
*
@@ -2694,247 +160,16 @@
return YCPBoolean(true);
}
-/*
- * A helper function - remove all resolvables from the repository from the pool
- */
-void PkgModuleFunctions::RemoveResolvablesFrom(const std::string &alias)
-{
- // remove the resolvables if they have been loaded
- // FIXME: can be implemented better? we need a ResStore object for removing,
- // which means search for a resolvable in the pool and get the Repository
- // object which can be asked for all resolvables in it
- for (zypp::ResPool::const_iterator it = zypp_ptr()->pool().begin()
- ; it != zypp_ptr()->pool().end()
- ; ++it)
- {
- if (it->resolvable()->repository().info().alias() == alias)
- {
- y2milestone("Removing all resolvables from '%s' from the pool...", alias.c_str());
- zypp_ptr()->removeResolvables(it->resolvable()->repository().resolvables());
- break;
- }
- }
-}
-
-/*
- * A helper function - is there any resolvable from the repository in the pool?
- */
-bool PkgModuleFunctions::AnyResolvableFrom(const std::string &alias)
-{
- for (zypp::ResPool::const_iterator it = zypp_ptr()->pool().begin()
- ; it != zypp_ptr()->pool().end()
- ; ++it)
- {
- if (it->resolvable()->repository().info().alias() == alias)
- {
- return true;
- }
- }
-
- return false;
-}
-
-/*
- * A helper function - load resolvable from the repository into the pool
- * Warning: Use AnyResolvableFrom() method for checing if the resolvables might be already loaded
+/**
+ * @builtin InstSysMode
+ * @short obsoleted - do not use
+ * @return void
*/
-bool PkgModuleFunctions::LoadResolvablesFrom(const zypp::RepoInfo &repoinfo)
-{
- bool success = true;
- unsigned int size_start = zypp_ptr()->pool().size();
- y2milestone("Loading resolvables from '%s', pool size at start: %d", repoinfo.alias().c_str(), size_start);
-
- try
- {
- zypp::RepoManager repomanager = CreateRepoManager();
-
- // build cache if needed
- if (!repomanager.isCached(repoinfo))
- {
- zypp::RepoStatus raw_metadata_status = repomanager.metadataStatus(repoinfo);
- if (raw_metadata_status.empty())
- {
- y2milestone("Missing metadata for source '%s', downloading...", repoinfo.alias().c_str());
- RefreshWithCallbacks(repoinfo);
- }
-
- y2milestone("Caching source '%s'...", repoinfo.alias().c_str());
- repomanager.buildCache(repoinfo);
- }
-
- zypp::Repository repository = repomanager.createFromCache(repoinfo);
- const zypp::ResStore &store = repository.resolvables();
-
- // load resolvables
- zypp_ptr()->addResolvables(store);
-
- y2milestone("Loaded %zd resolvables", store.size());
- }
- catch(const zypp::repo::RepoNotCachedException &excpt )
- {
- std::string alias = repoinfo.alias();
- y2error ("Resolvables from '%s' havn't been loaded: %s", alias.c_str(), excpt.asString().c_str());
- _last_error.setLastError("'" + alias + "': " + ExceptionAsString(excpt));
- success = false;
-
- // FIXME ??
- /*
- // disable the source
- y2error("Disabling source %s", url.c_str());
- repo->disable();
- */
- }
- catch (const zypp::Exception& excpt)
- {
- std::string alias = repoinfo.alias();
- y2internal("Error: Loading resolvables failed: %s", ExceptionAsString(excpt).c_str());
- _last_error.setLastError("'" + alias + "': " + ExceptionAsString(excpt));
- success = false;
- }
-
- unsigned int size_end = zypp_ptr()->pool().size();
- y2milestone("Pool size at end: %d (loaded %d resolvables)", size_end, size_end - size_start);
- return success;
-}
-
-/****************************************************************************************
- * @builtin RepositoryProbe
- *
- * @short Probe type of the repository
- * @param url specifies the path to the repository
- * @param prod_dir product directory (if empty the url is probed directly)
- * @return string repository type ("NONE" if type could be determined, nil if an error occurred (e.g. resolving the hostname)
- **/
-YCPValue PkgModuleFunctions::RepositoryProbe(const YCPString& url, const YCPString& prod_dir)
-{
- y2milestone("Probing repository type: '%s'...", url->value().c_str());
- zypp::RepoManager repomanager = CreateRepoManager();
- std::string ret;
-
- try
- {
- zypp::Url probe_url(url->value());
-
- // add the product directory
- std::string prod = prod_dir->value();
-
- if (!prod.empty())
- {
- // add "/" at the begining if it's missing
- if (std::string(prod, 0, 1) != "/")
- {
- prod = "/" + prod;
- }
-
- // merge the URL path and the product path
- std::string path = probe_url.getPathName();
- path += prod;
-
- y2milestone("Using probing path: %s", path.c_str());
- probe_url.setPathName(path);
- }
-
- // add "ro" mount option
- probe_url = addRO(probe_url);
-
- // autoprobe type of the repository
- zypp::repo::RepoType repotype = ProbeWithCallbacks(probe_url);
-
- ret = zypp2yastType(repotype.asString());
- y2milestone("Detected type: '%s'...", ret.c_str());
- }
- catch (const zypp::Exception& excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error( "Cannot detect the repository type" );
- return YCPVoid();
- }
-
- return YCPString(ret);
-}
-
-/****************************************************************************************
- * @builtin RepositoryScan
- *
- * @short Scan available products in the repository
- * @param url specifies the path to the repository
- * @return list<list<string>> list of the products: [ [ <product_name_1> <directory_1> ], ...]
- **/
-YCPValue PkgModuleFunctions::RepositoryScan(const YCPString& url)
-{
- zypp::MediaProductSet products;
-
- try
- {
- zypp::Url baseurl(url->value());
-
- baseurl = addRO(baseurl);
-
- ScanProductsWithCallBacks(baseurl);
- products = available_products;
- }
- catch ( const zypp::Exception& excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error( "Cannot read the product list from the media" );
- return YCPList();
- }
-
- YCPList ret;
-
- for( zypp::MediaProductSet::const_iterator it = products.begin();
- it != products.end() ; ++it )
- {
- YCPList prod;
-
- // add product directory
- prod.add(YCPString(it->_name));
- // add product name
- prod.add(YCPString(it->_dir.asString()));
-
- ret.add(prod);
- }
-
- y2milestone("Found products: %s", ret->toString().c_str());
-
- return ret;
-}
-
-// convert libzypp type to yast strings ("YaST", "YUM" or "Plaindir")
-std::string PkgModuleFunctions::zypp2yastType(const std::string &type)
+YCPValue
+PkgModuleFunctions::InstSysMode ()
{
- std::string ret(type);
-
- if (type_conversion_table.empty())
- {
- // initialize the conversion map
- type_conversion_table["rpm-md"] = "YUM";
- type_conversion_table["yast2"] = "YaST";
- type_conversion_table["plaindir"] = "Plaindir";
- type_conversion_table["NONE"] = "NONE";
- }
-
- std::map<std::string,std::string>::const_iterator it = type_conversion_table.find(type);
-
- // found in the conversion table
- if (it != type_conversion_table.end())
- {
- ret = it->second;
- }
- else
- {
- y2error("Cannot convert type '%s'", type.c_str());
- }
-
- return ret;
+ y2warning("Pkg::InstSysMode() is obsoleted, it's not needed anymore");
+ return YCPVoid();
}
-std::string PkgModuleFunctions::yast2zyppType(const std::string &type)
-{
- // do conversion from the Yast type ("YaST", "YUM", "Plaindir")
- // to libzypp type ("yast", "yum", "plaindir")
- // we can simply use toLower instead of a conversion table
- // in this case
- return zypp::str::toLower(type);
-}
Copied: trunk/pkg-bindings/src/Source_Load.cc (from r42708, trunk/pkg-bindings/src/Source.cc)
URL: http://svn.opensuse.org/viewcvs/yast/trunk/pkg-bindings/src/Source_Load.cc?…
==============================================================================
--- trunk/pkg-bindings/src/Source.cc (original)
+++ trunk/pkg-bindings/src/Source_Load.cc Thu Dec 6 07:56:58 2007
@@ -1,329 +1,37 @@
-/*---------------------------------------------------------------------\
-| |
-| __ __ ____ _____ ____ |
-| \ \ / /_ _/ ___|_ _|___ \ |
-| \ V / _` \___ \ | | __) | |
-| | | (_| |___) || | / __/ |
-| |_|\__,_|____/ |_| |_____| |
-| |
-| core system |
-| (C) SuSE GmbH |
-\----------------------------------------------------------------------/
-
- File: PkgModuleFunctionsSource.cc
-
- Author: Klaus Kaempf <kkaempf(a)suse.de>
- Maintainer: Klaus Kaempf <kkaempf(a)suse.de>
-
- Summary: Access to Installation Sources
- Namespace: Pkg
- Purpose: Access to InstSrc
- Handles source related Pkg::function (list_of_arguments) calls
- from WFMInterpreter.
-/-*/
-//#include <unistd.h>
-//#include <sys/statvfs.h>
-
-#include <iostream>
+/* ------------------------------------------------------------------------------
+ * Copyright (c) 2007 Novell, Inc. All Rights Reserved.
+ *
+ *
+ * This program is free software; you can redistribute it and/or modify it under
+ * the terms of version 2 of the GNU General Public License as published by the
+ * Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+ * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along with
+ * this program; if not, contact Novell, Inc.
+ *
+ * To contact Novell about this file by physical or electronic mail, you may find
+ * current contact information at www.novell.com.
+ * ------------------------------------------------------------------------------
+ */
-#include <ycpTools.h>
-#include <PkgModule.h>
-#include <PkgModuleFunctions.h>
+/*
+ File: $Id:$
+ Author: Ladislav Slezák <lslezak(a)novell.com>
+ Summary: Functions for initializing the package manager
+*/
#include <Callbacks.h>
#include <Callbacks.YCP.h>
-#include <zypp/Product.h>
-#include <zypp/media/MediaManager.h>
-#include <zypp/media/Mount.h>
-#include <zypp/Pathname.h>
-
-#include <zypp/RepoInfo.h>
-#include <zypp/RepoManager.h>
-#include <zypp/Fetcher.h>
-#include <zypp/repo/RepoType.h>
-#include <zypp/MediaProducts.h>
-#include <zypp/ExternalProgram.h>
-#include <zypp/ProgressData.h>
-
-#include <sstream> // ostringstream
+#include <PkgModule.h>
+#include <PkgModuleFunctions.h>
#include <PkgProgress.h>
-/*
- Textdomain "pkg-bindings"
-*/
-
-// scanned available products
-// hack: zypp/MediaProducts.h cannot be included in PkgModuleFunctions.h
-zypp::MediaProductSet available_products;
-
-// this method should be used instead of zypp::productsInMedia()
-// it initializes the download callbacks
-void PkgModuleFunctions::ScanProductsWithCallBacks(const zypp::Url &url)
-{
- CallInitDownload(std::string(_("Scanning products in ") + url.asString()));
-
- extern ZyppRecipients::MediaChangeSensitivity _silent_probing;
- // remember the current value
- ZyppRecipients::MediaChangeSensitivity _silent_probing_old = _silent_probing;
-
- // disable media change callback for optional file
- _silent_probing = ZyppRecipients::MEDIA_CHANGE_DISABLE;
-
- y2milestone("Scanning products in %s ...", url.asString().c_str());
-
- try
- {
- available_products.clear();
- zypp::productsInMedia(url, available_products);
- }
- catch(...)
- {
- // call the final event even in case of exception
- CallDestDownload();
-
- // restore the probing flag
- _silent_probing = _silent_probing_old;
-
- // rethrow the execption
- throw;
- }
-
- CallDestDownload();
-
- // restore the probing flag
- _silent_probing = _silent_probing_old;
-}
-
-void PkgModuleFunctions::CallSourceReportStart(const std::string &text)
-{
- // get the YCP callback handler
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_SourceReportStart);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- // add parameters
- ycp_handler->appendParameter( YCPInteger(0LL) );
- ycp_handler->appendParameter( YCPString("") );
- ycp_handler->appendParameter( YCPString(text) );
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-
-void PkgModuleFunctions::CallSourceReportEnd(const std::string &text)
-{
- // get the YCP callback handler for end event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_SourceReportEnd);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- // add parameters
- ycp_handler->appendParameter( YCPInteger(0LL) );
- ycp_handler->appendParameter( YCPString("") );
- ycp_handler->appendParameter( YCPString(text) );
- ycp_handler->appendParameter( YCPString("NO_ERROR") );
- ycp_handler->appendParameter( YCPString("") );
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-
-void PkgModuleFunctions::CallSourceReportInit()
-{
- // get the YCP callback handler for init event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_SourceReportInit);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-
-void PkgModuleFunctions::CallSourceReportDestroy()
-{
- // get the YCP callback handler for destroy event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_SourceReportDestroy);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-
-void PkgModuleFunctions::CallInitDownload(const std::string &task)
-{
- // get the YCP callback handler for destroy event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_InitDownload);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- ycp_handler->appendParameter(YCPString(task));
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-
-void PkgModuleFunctions::CallDestDownload()
-{
- // get the YCP callback handler for destroy event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_DestDownload);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-
-// this method should be used instead of RepoManager::refreshMetadata()
-void PkgModuleFunctions::RefreshWithCallbacks(const zypp::RepoInfo &repo)
-{
- CallInitDownload(std::string(_("Refreshing repository ") + repo.alias()));
-
- try
- {
- zypp::RepoManager repomanager = CreateRepoManager();
- repomanager.refreshMetadata(repo);
- }
- catch(...)
- {
- // call the final event even in case of exception
- CallDestDownload();
- // rethrow the execption
- throw;
- }
-
- CallDestDownload();
-}
-
-// this method should be used instead of RepoManager::probe()
-zypp::repo::RepoType PkgModuleFunctions::ProbeWithCallbacks(const zypp::Url &url)
-{
- CallInitDownload(std::string(_("Probing repository ") + url.asString()));
-
- zypp::repo::RepoType repotype;
-
- extern ZyppRecipients::MediaChangeSensitivity _silent_probing;
- // remember the current value
- ZyppRecipients::MediaChangeSensitivity _silent_probing_old = _silent_probing;
-
- // disable media change callback for optional file
- _silent_probing = ZyppRecipients::MEDIA_CHANGE_DISABLE;
-
- try
- {
- // probe type of the repository
- zypp::RepoManager repomanager = CreateRepoManager();
- repotype = repomanager.probe(url);
- }
- catch(...)
- {
- // call the final event even in case of exception
- CallDestDownload();
-
- // restore the probing flag
- _silent_probing = _silent_probing_old;
-
- // rethrow the execption
- throw;
- }
-
- CallDestDownload();
-
- // restore the probing flag
- _silent_probing = _silent_probing_old;
-
- return repotype;
-}
-
-/**
- * Logging helper:
- * call zypp::SourceManager::sourceManager()->findSource
- * and in case of exception, log error and setLastError AND RETHROW
- */
-YRepo_Ptr PkgModuleFunctions::logFindRepository(std::vector<YRepo_Ptr>::size_type id)
-{
- try
- {
- if (id < 0 || id >= repos.size())
- {
- // not found
- throw(std::exception());
- }
-
- if (!repos[id])
- {
- // not found
- throw(std::exception());
- }
-
- if (repos[id]->isDeleted())
- {
- y2error("Source %zd has been deleted, the ID is not valid", id);
- return YRepo_Ptr();
- }
-
- return repos[id];
- }
- catch (...)
- {
- y2error("Cannot find source with ID: %zd", id);
- // TODO: improve the error message
- _last_error.setLastError(_("Cannot find source"));
- }
-
- // not found, return empty pointer
- return YRepo_Ptr();
-}
-
-long long PkgModuleFunctions::logFindAlias(const std::string &alias) const
-{
- std::vector<YRepo_Ptr>::size_type index = 0;
-
- for(std::vector<YRepo_Ptr>::const_iterator it = repos.begin(); it != repos.end() ; ++it, ++index)
- {
- if (!(*it)->isDeleted() && (*it)->repoInfo().alias() == alias)
- return index;
- }
-
- return -1LL;
-}
-
-bool PkgModuleFunctions::aliasExists(const std::string &alias) const
-{
- for(std::vector<YRepo_Ptr>::const_iterator it = repos.begin(); it != repos.end() ; ++it)
- {
- if (!(*it)->isDeleted() && (*it)->repoInfo().alias() == alias)
- return true;
- }
-
- return false;
-}
-
-/****************************************************************************************
- * @builtin SourceSetRamCache
- * @short Obsoleted function, do not use
- * @param boolean
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceSetRamCache (const YCPBoolean& a)
-{
- y2warning( "Pkg::SourceSetRamCache is obsolete and does nothing");
- return YCPBoolean( true );
-}
-
-
/****************************************************************************************
* @builtin SourceRestore
*
@@ -710,2231 +418,3 @@
y2warning("Pkg::SourceCleanupBroken() is obsoleted, it's not needed anymore.");
return YCPBoolean(true);
}
-
-/****************************************************************************************
- * @builtin SourceGetCurrent
- *
- * @short Return the list of all InstSrc Ids.
- *
- * @param boolean enabled_only If true, or omitted, return the Ids of all enabled InstSrces.
- * If false, return the Ids of all known InstSrces.
- *
- * @return list<integer> list of SrcIds (integer)
- **/
-YCPValue
-PkgModuleFunctions::SourceGetCurrent (const YCPBoolean& enabled)
-{
- YCPList res;
-
- std::vector<YRepo_Ptr>::size_type index = 0;
- for( std::vector<YRepo_Ptr>::const_iterator it = repos.begin(); it != repos.end() ; ++it, ++index )
- {
- // ignore disabled sources if requested
- if (enabled->value())
- {
- // Note: enabled() is tribool!
- if ((*it)->repoInfo().enabled())
- {
- }
- else if (!(*it)->repoInfo().enabled())
- {
- continue;
- }
- else
- {
- continue;
- }
- }
-
- // ignore deleted sources
- if ((*it)->isDeleted())
- {
- continue;
- }
-
- res->add( YCPInteger(index) );
- }
-
- return res;
-}
-
-/****************************************************************************************
- * @builtin SourceReleaseAll
- *
- * @short Release all medias hold by all sources
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceReleaseAll ()
-{
- y2milestone("Releasing all sources...");
- bool ret = true;
-
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- try
- {
- (*it)->mediaAccess()->release();
- }
- catch (const zypp::media::MediaException & ex)
- {
- y2warning("Failed to release media for repo: %s", ex.msg().c_str());
- ret = false;
- }
- }
-
- return YCPBoolean(ret);
-}
-
-/******************************************************************************
- * @builtin SourceSaveAll
- *
- * @short Save all InstSrces.
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceSaveAll ()
-{
- y2milestone("Saving the source setup...");
-
- zypp::RepoManager repomanager = CreateRepoManager();
-
- // remove deleted repos (the old configurations) at first
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- // the repo has been removed
- if ((*it)->isDeleted())
- {
- std::string repo_alias = (*it)->repoInfo().alias();
-
- try
- {
- // remove the metadata
- zypp::RepoStatus raw_metadata_status = repomanager.metadataStatus((*it)->repoInfo());
- if (!raw_metadata_status.empty())
- {
- y2milestone("Removing metadata for source '%s'...", repo_alias.c_str());
- repomanager.cleanMetadata((*it)->repoInfo());
- }
-
- // remove the cache
- if (repomanager.isCached((*it)->repoInfo()))
- {
- y2milestone("Removing cache for '%s'...", repo_alias.c_str());
- repomanager.cleanCache((*it)->repoInfo());
- }
-
- repomanager.getRepositoryInfo(repo_alias);
- y2milestone("Removing repository '%s'", repo_alias.c_str());
- repomanager.removeRepository((*it)->repoInfo());
- }
- catch (const zypp::repo::RepoNotFoundException &ex)
- {
- // repository not found -- not critical, continue
- y2warning("No such repository: %s", repo_alias.c_str());
- }
- catch (const zypp::Exception & excpt)
- {
- y2error("Pkg::SourceSaveAll has failed: %s", excpt.msg().c_str() );
- _last_error.setLastError(ExceptionAsString(excpt));
- return YCPBoolean(false);
- }
- }
- }
-
- // save all repos (the current configuration)
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- if (!(*it)->isDeleted())
- {
- std::string current_alias = (*it)->repoInfo().alias();
-
- try
- {
- try
- {
- // if the repository already exists then just modify it
- repomanager.getRepositoryInfo(current_alias);
- y2milestone("Modifying repository '%s'", current_alias.c_str());
- repomanager.modifyRepository(current_alias, (*it)->repoInfo());
- }
- catch (const zypp::repo::RepoNotFoundException &ex)
- {
- // the repository was not found, add it
- y2milestone("Adding repository '%s'", current_alias.c_str());
- repomanager.addRepository((*it)->repoInfo());
- }
- }
- catch (zypp::Exception & excpt)
- {
- y2error("Pkg::SourceSaveAll has failed: %s", excpt.msg().c_str() );
- _last_error.setLastError(ExceptionAsString(excpt));
- return YCPBoolean(false);
- }
- }
- }
-
- y2milestone("All sources have been saved");
-
- return YCPBoolean(true);
-}
-
-/****************************************************************************************
- * @builtin SourceFinishAll
- *
- * @short Save and then disable all InstSrces.
- * @description
- * If there are no enabled sources, do nothing
- * (idempotence hack, broken design: #155459, #176013, use SourceSaveAll).
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceFinishAll ()
-{
- try
- {
- bool found_enabled = false;
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
- {
- found_enabled = true;
- break;
- }
- }
-
- if (!found_enabled)
- {
- y2milestone( "No enabled sources, skipping SourceFinishAll()" );
- return YCPBoolean( true );
- }
-
- SourceSaveAll();
-
- y2milestone( "Disabling all sources...") ;
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- (*it)->repoInfo().setEnabled(false);
- }
- // TODO FIXME remove all resolvables??
- }
- catch (zypp::Exception & excpt)
- {
- y2error("Pkg::SourceFinishAll has failed: %s", excpt.msg().c_str() );
- _last_error.setLastError(ExceptionAsString(excpt));
- return YCPBoolean(false);
- }
-
- y2milestone("All sources have been saved and disabled");
-
- return YCPBoolean(true);
-}
-
-/////////////////////////////////////////////////////////////////////////////////////////
-// Query individual sources
-/////////////////////////////////////////////////////////////////////////////////////////
-
-/****************************************************************************************
- * @builtin SourceGeneralData
- *
- * @short Get general data about the source
- * @description
- * Return general data about the source as a map:
- *
- * <code>
- * $[
- * "enabled" : YCPBoolean,
- * "autorefresh": YCPBoolean,
- * "product_dir": YCPString,
- * "type" : YCPString,
- * "url" : YCPString (without password, but see SourceURL),
- * "alias" : YCPString,
- * "name" : YCPString,
- * ];
- *
- * </code>
- * @param integer SrcId Specifies the InstSrc to query.
- * @return map
- **/
-YCPValue
-PkgModuleFunctions::SourceGeneralData (const YCPInteger& id)
-{
- YCPMap data;
-
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPVoid ();
-
- // convert type to the old strings ("YaST", "YUM" or "Plaindir")
- std::string srctype = zypp2yastType(repo->repoInfo().type().asString());
-
- data->add( YCPString("enabled"), YCPBoolean(repo->repoInfo().enabled()));
- data->add( YCPString("autorefresh"), YCPBoolean(repo->repoInfo().autorefresh()));
- data->add( YCPString("type"), YCPString(srctype));
- data->add( YCPString("product_dir"), YCPString(repo->repoInfo().path().asString()));
-
- // check if there is an URL
- if (repo->repoInfo().baseUrlsBegin() != repo->repoInfo().baseUrlsEnd())
- {
- data->add( YCPString("url"), YCPString(repo->repoInfo().baseUrlsBegin()->asString()));
- }
-
- data->add( YCPString("alias"), YCPString(repo->repoInfo().alias()));
- data->add( YCPString("name"), YCPString(repo->repoInfo().name()));
-
- YCPList base_urls;
- for( zypp::RepoInfo::urls_const_iterator it = repo->repoInfo().baseUrlsBegin(); it != repo->repoInfo().baseUrlsEnd(); ++it)
- {
- base_urls->add(YCPString(it->asString()));
- }
- data->add( YCPString("base_urls"), base_urls);
-
- data->add( YCPString("mirror_list"), YCPString(repo->repoInfo().mirrorListUrl().asString()));
-
- return data;
-}
-
-/******************************************************************************
- * @builtin SourceURL
- *
- * @short Get full source URL, including password
- * @param integer SrcId Specifies the InstSrc to query.
- * @return string or nil on failure
- **/
-YCPValue
-PkgModuleFunctions::SourceURL (const YCPInteger& id)
-{
-
- const YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPVoid();
-
- std::string url;
-
- if (repo->repoInfo().baseUrlsBegin() != repo->repoInfo().baseUrlsEnd())
- {
- // #186842
- url = repo->repoInfo().baseUrlsBegin()->asCompleteString();
- }
-
- return YCPString(url);
-}
-
-/****************************************************************************************
- * @builtin SourceMediaData
- * @short Return media data about the source
- * @description
- * Return media data about the source as a map:
- *
- * <code>
- * $["media_count": YCPInteger,
- * "media_id" : YCPString,
- * "media_vendor" : YCPString,
- * "url" : YCPString,
- * ];
- * </code>
- *
- * @param integer SrcId Specifies the InstSrc to query.
- * @return map
- **/
-YCPValue
-PkgModuleFunctions::SourceMediaData (const YCPInteger& id)
-{
- YCPMap data;
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPVoid ();
-
- std::string alias = repo->repoInfo().alias();
- bool found_resolvable = false;
- int max_medium = 1;
-
- for (zypp::ResPool::const_iterator it = zypp_ptr()->pool().begin()
- ; it != zypp_ptr()->pool().end()
- ; ++it)
- {
- if (it->resolvable()->repository().info().alias() == alias)
- {
- int medium = it->resolvable()->mediaNr();
-
- if (medium > max_medium)
- {
- max_medium = medium;
- }
- }
- }
-
- if (found_resolvable)
- {
- data->add( YCPString("media_count"), YCPInteger(max_medium));
- }
- else
- {
- y2error("No resolvable from repository '%s' found, cannot get number of media (use Pkg::SourceLoad() to load the resolvables)", alias.c_str());
- }
-
- y2warning("Pkg::SourceMediaData() doesn't return \"media_id\" and \"media_vendor\" values anymore.");
-
- // SourceMediaData returns URLs without password
- if (repo->repoInfo().baseUrlsBegin() != repo->repoInfo().baseUrlsEnd())
- {
- data->add( YCPString("url"), YCPString(repo->repoInfo().baseUrlsBegin()->asString()));
-
- // add all base URLs
- YCPList base_urls;
- for( zypp::RepoInfo::urls_const_iterator it = repo->repoInfo().baseUrlsBegin(); it != repo->repoInfo().baseUrlsEnd(); ++it)
- {
- base_urls->add(YCPString(it->asString()));
- }
- data->add( YCPString("base_urls"), base_urls);
- }
-
- return data;
-}
-
-/****************************************************************************************
- * @builtin SourceProductData
- * @short Return Product data about the source
- * @param integer SrcId Specifies the InstSrc to query.
- * @description
- * Product data about the source as a map:
- *
- * <code>
- * $[
- * "label" : YCPString,
- * "vendor" : YCPString,
- * "productname" : YCPString,
- * "productversion" : YCPString,
- * "relnotesurl" : YCPString,
- * ];
- * </code>
- *
- * @return map
- **/
-YCPValue
-PkgModuleFunctions::SourceProductData (const YCPInteger& src_id)
-{
- YCPMap ret;
-
- try
- {
- // find a product for the given source
- zypp::ResPool::byKind_iterator it = zypp_ptr()->pool().byKindBegin(zypp::ResTraits<zypp::Product>::kind);
-
- for( ; it != zypp_ptr()->pool().byKindEnd(zypp::ResTraits<zypp::Product>::kind) ; ++it)
- {
- zypp::Product::constPtr product = boost::dynamic_pointer_cast<const zypp::Product>( it->resolvable() );
-
- if( logFindAlias(product->repository().info().alias()) == src_id->value() )
- {
- ret->add( YCPString("label"), YCPString( product->summary() ) );
- ret->add( YCPString("vendor"), YCPString( product->vendor() ) );
- ret->add( YCPString("productname"), YCPString( product->name() ) );
- ret->add( YCPString("productversion"), YCPString( product->edition().version() ) );
- ret->add( YCPString("relnotesurl"), YCPString( product->releaseNotesUrl().asString()));
-
- #warning SourceProductData not finished
- /*
- data->add( YCPString("datadir"), YCPString( descr->content_datadir().asString() ) );
- TODO (?): "baseproductname", "baseproductversion", "defaultbase", "architectures",
- "requires", "linguas", "labelmap", "language", "timezone", "descrdir", "datadir"
- */
-
- break;
- }
- }
-
- if( it == zypp_ptr()->pool().byKindEnd(zypp::ResTraits<zypp::Product>::kind) )
- {
- y2error ("Product for source '%lld' not found", src_id->value());
- }
- }
- catch (...)
- {
- }
-
- return ret;
-}
-
-/****************************************************************************************
- * @builtin SourceProduct
- * @short Obsoleted function, do not use, see SourceProductData builtin
- * @deprecated
- * @param integer
- * @return map empty map
- **/
-YCPValue
-PkgModuleFunctions::SourceProduct (const YCPInteger& id)
-{
- /* TODO FIXME */
- y2error("Pkg::SourceProduct() is obsoleted, use Pkg::SourceProductData() instead!");
- return YCPMap();
-}
-
-
-YCPValue PkgModuleFunctions::SourceProvideFileCommon(const YCPInteger &id,
- const YCPInteger &mid,
- const YCPString& f,
- const YCPBoolean & optional)
-{
- CallInitDownload(std::string(_("Downloading ") + f->value()));
-
- bool found = true;
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- found = false;
-
- extern ZyppRecipients::MediaChangeSensitivity _silent_probing;
- // remember the current value
- ZyppRecipients::MediaChangeSensitivity _silent_probing_old = _silent_probing;
-
- // disable media change callback for optional file
- if (optional->value())
- _silent_probing = ZyppRecipients::MEDIA_CHANGE_OPTIONALFILE;
-
- zypp::filesystem::Pathname path; // FIXME use ManagedMedia
- if (found)
- {
- try
- {
- path = repo->mediaAccess()->provideFile(f->value(), mid->value());
- y2milestone("local path: '%s'", path.asString().c_str());
- }
- catch (const zypp::Exception& excpt)
- {
- found = false;
-
- if (!optional->value())
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2milestone("File not found: %s", f->value_cstr());
- }
- }
- }
-
- // set the original probing value
- _silent_probing = _silent_probing_old;
-
- CallDestDownload();
-
- if (found)
- {
- return YCPString(path.asString());
- }
- else
- {
- return YCPVoid();
- }
-}
-
-
-/****************************************************************************************
- * @builtin SourceProvideFile
- *
- * @short Make a file available at the local filesystem
- * @description
- * Let an InstSrc provide some file (make it available at the local filesystem).
- *
- * @param integer SrcId Specifies the InstSrc .
- * @param integer medianr Number of the media the file is located on ('1' for the 1st media).
- * @param string file Filename relative to the media root.
- *
- * @return string local path as string
- **/
-YCPValue
-PkgModuleFunctions::SourceProvideFile (const YCPInteger& id, const YCPInteger& mid, const YCPString& f)
-{
- return SourceProvideFileCommon(id, mid, f, false /*optional*/);
-}
-
-/****************************************************************************************
- * @builtin SourceProvideOptionalFile
- *
- * @short Make an optional file available at the local filesystem
- * @description
- * Let an InstSrc provide some file (make it available at the local filesystem).
- * If the file doesn't exist don't ask user for another medium and return nil
- *
- * @param integer SrcId Specifies the InstSrc .
- * @param integer medianr Number of the media the file is located on ('1' for the 1st media).
- * @param string file Filename relative to the media root.
- *
- * @return string local path as string
- **/
-YCPValue
-PkgModuleFunctions::SourceProvideOptionalFile (const YCPInteger& id, const YCPInteger& mid, const YCPString& f)
-{
- return SourceProvideFileCommon(id, mid, f, true /*optional*/);
-}
-
-/****************************************************************************************
- * @builtin SourceProvideDir
- * @short make a directory available at the local filesystem
- * @description
- * Let an InstSrc provide some directory (make it available at the local filesystem) and
- * all the files within it (non recursive).
- *
- * @param integer SrcId Specifies the InstSrc .
- * @param integer medianr Number of the media the file is located on ('1' for the 1st media).
- * @param string dir Directoryname relative to the media root.
- * @return string local path as string
- */
-YCPValue
-PkgModuleFunctions::SourceProvideDir (const YCPInteger& id, const YCPInteger& mid, const YCPString& d)
-{
- y2warning("Pkg::SourceProvideDir() is obsoleted use Pkg::SourceProvideDirectory() instead");
- // non optional, non recursive
- return SourceProvideDirectory(id, mid, d, false, false);
-}
-
-
-/****************************************************************************************
- * @builtin SourceProvideDirectory
- * @short make a directory available at the local filesystem
- * @description
- * Download a directory from repository (make it available at the local filesystem) and
- * all the files within it.
- *
- * @param integer id repository to use (id)
- * @param integer mid Number of the media where the directory is located on ('1' for the 1st media).
- * @param string d Directory name relative to the media root.
- * @param boolean optional set to true if the directory may not exist (do not report errors)
- * @param boolean recursive set to true to provide all subdirectories recursively
- * @return string local path as string or nil when an error occured
- */
-YCPValue
-PkgModuleFunctions::SourceProvideDirectory(const YCPInteger& id, const YCPInteger& mid, const YCPString& d, const YCPBoolean &optional, const YCPBoolean &recursive)
-{
- CallInitDownload(std::string(_("Downloading ") + d->value()));
-
- bool found = true;
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- found = false;
-
- zypp::filesystem::Pathname path; // FIXME user ManagedMedia
-
- extern ZyppRecipients::MediaChangeSensitivity _silent_probing;
- // remember the current value
- ZyppRecipients::MediaChangeSensitivity _silent_probing_old = _silent_probing;
-
- // disable media change callback for optional file
- if (optional->value())
- _silent_probing = ZyppRecipients::MEDIA_CHANGE_OPTIONALFILE;
-
- if (found)
- {
- try
- {
- path = repo->mediaAccess()->provideDir(d->value(), recursive->value(), mid->value());
- }
- catch (const zypp::Exception& excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2milestone ("Directory not found: %s", d->value_cstr());
- found = false;
- }
- }
-
- // set the original probing value
- _silent_probing = _silent_probing_old;
-
- CallDestDownload();
-
- if (found)
- {
- return YCPString(path.asString());
- }
- else
- {
- return YCPVoid();
- }
-}
-
-/****************************************************************************************
- * @builtin SourceChangeUrl
- * @short Change Source URL
- * @description
- * Change url of an InstSrc. Used primarely when re-starting during installation
- * and a cd-device changed from hdX to srX since ide-scsi was activated.
- * @param integer SrcId Specifies the InstSrc.
- * @param string url The new url to use.
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceChangeUrl (const YCPInteger& id, const YCPString& u)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- try
- {
- if (repo->repoInfo().baseUrlsSize() > 1)
- {
- // store current urls
- std::set<zypp::Url> baseUrls (repo->repoInfo().baseUrlsBegin(), repo->repoInfo().baseUrlsEnd());
-
- // reset url list and store the new one there
- repo->repoInfo().setBaseUrl(zypp::Url(u->value()));
-
- // add the rest of base urls
- for (std::set<zypp::Url>::const_iterator i = baseUrls.begin();
- i != baseUrls.end(); ++i)
- repo->repoInfo().addBaseUrl(*i);
- }
- else
- repo->repoInfo().setBaseUrl(zypp::Url(u->value()));
- }
- catch (const zypp::Exception & excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error ("Cannot set the new URL for source %s (%lld): %s",
- repo->repoInfo().alias().c_str(), id->asInteger()->value(), excpt.msg().c_str());
- return YCPBoolean(false);
- }
-
- return YCPBoolean(true);
-}
-
-/****************************************************************************************
- * @builtin SourceInstallOrder
- *
- * @short not implemented, do not use (Explicitly set an install order.)
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceInstallOrder (const YCPMap& ord)
-{
- /* TODO FIXME
- YCPList args;
- args->add (ord);
-
- //-------------------------------------------------------------------------------------//
- YcpArgLoad decl(__FUNCTION__);
-
- YCPMap & order_map( decl.arg<YT_MAP, YCPMap>() );
-
- if ( ! decl.load( args ) ) {
- return pkgError_bad_args;
- }
- //-------------------------------------------------------------------------------------//
-
- InstSrcManager::InstOrder order;
- order.reserve( order_map->size() );
- bool error = false;
-
- for ( YCPMapIterator it = order_map->begin(); it != order_map->end(); ++it ) {
-
- if ( it.value()->isInteger() ) {
- InstSrc::UniqueID uId( it.value()->asInteger()->value() );
- InstSrcManager::ISrcId source_id( _y2pm.instSrcManager().getSourceByID( uId ) );
- if ( source_id ) {
- if ( source_id->enabled() ) {
- order.push_back( uId ); // finaly ;)
-
- } else {
- y2error ("order map entry '%s:%s': source not enabled",
- it.key()->toString().c_str(),
- it.value()->toString().c_str() );
- error = true;
- }
- } else {
- y2error ("order map entry '%s:%s': bad source id",
- it.key()->toString().c_str(),
- it.value()->toString().c_str() );
- error = true;
- }
- } else {
- y2error ("order map entry '%s:%s': integer value expected",
- it.key()->toString().c_str(),
- it.value()->toString().c_str() );
- error = true;
- }
- }
- if ( error ) {
- return pkgError( Error::E_bad_args );
- }
-
- // store new instorder
- _y2pm.instSrcManager().setInstOrder( order );
-*/
-
-#warning SourceInstallOrder is not implemented
- return YCPBoolean( true );
-}
-
-
-static std::string timestamp ()
-{
- time_t t = time(NULL);
- struct tm * tmp = localtime(&t);
-
- if (tmp == NULL) {
- return "";
- }
-
- char outstr[50];
- if (strftime(outstr, sizeof(outstr), "%Y%m%d-%H%M%S", tmp) == 0) {
- return "";
- }
- return outstr;
-}
-
-/**
- * Take the ?alias=foo part of old_url, if any, and return it,
- * putting the rest to new_url.
- * \throws Exception on malformed URLs I guess
- */
-static std::string removeAlias (const zypp::Url & old_url,
- zypp::Url & new_url)
-{
- std::string alias;
- new_url = old_url;
- zypp::url::ParamMap query = new_url.getQueryStringMap ();
- zypp::url::ParamMap::iterator alias_it = query.find ("alias");
- if (alias_it != query.end ())
- {
- alias = alias_it->second;
- query.erase (alias_it);
- new_url.setQueryStringMap (query);
- }
- return alias;
-}
-
-std::string PkgModuleFunctions::UniqueAlias(const std::string &alias)
-{
- // make a copy
- std::string ret = alias;
-
- unsigned int id = 0;
- while(aliasExists(ret))
- {
- y2milestone("Alias %s already found: %lld", ret.c_str(), logFindAlias(ret));
-
- // the alias already exists - add a counter
- std::ostringstream ostr;
- ostr << alias << "_" << id;
-
- ret = ostr.str();
-
- y2milestone("Using alias %s", ret.c_str());
- ++id;
- }
-
- return ret;
-}
-
-
-/**
- * helper - add "mountoptions=ro" for mountable URL schemes if "mountoptions" option is not empty and
- * "rw" or "ro" option is missing
- */
-zypp::Url addRO(const zypp::Url &url)
-{
- zypp::Url ret(url);
- std::string scheme = zypp::str::toLower(url.getScheme());
-
- if (scheme == "nfs"
- || scheme == "hd"
- || scheme == "smb"
- || scheme == "iso"
- || scheme == "cd"
- || scheme == "dvd"
- )
- {
- const std::string mountoptions = "mountoptions";
- zypp::media::Mount::Options options(url.getQueryParam(mountoptions));
-
- y2debug("Current mountoptions: %s", options.asString().c_str());
-
- // if mountoptions are empty lizypp uses "ro" by default
- // don't override "rw" option from application
- // don't add "ro" if it's already present
- if (!options.empty() && !options.has("rw") && !options.has("ro"))
- {
- options["ro"];
-
- ret.setQueryParam(mountoptions, options.asString());
- y2milestone("Adding read only mount option: '%s' -> '%s'", url.asString().c_str(), ret.asString().c_str());
- }
- }
-
- return ret;
-}
-
-// helper function
-zypp::Url PkgModuleFunctions::shortenUrl(const zypp::Url &url)
-{
- std::string url_path = url.getPathName();
- std::string begin_path;
- std::string end_path;
-
- // try to convert 'http://server/dir1/dir2/dir3/dir4' -> 'http://server/dir1/.../dir4'
- std::string::size_type pos_first = url_path.find("/");
- if (pos_first == 0)
- {
- pos_first = url_path.find("/", 1);
- }
-
- if (pos_first == std::string::npos)
- {
- const int num = 5;
-
- // "/" not found use the beginning and the end part
- // 'http://server/very_long_directory_name' -> 'http://server/very_..._name'
- begin_path = std::string(url_path, 0, num);
- end_path = std::string(url_path, url_path.size() - num - 1, num);
- }
- else
- {
- unsigned int pos_last = url_path.rfind("/");
- if (pos_last == url_path.size() - 1)
- {
- pos_last = url_path.rfind("/", url_path.size() - 1);
- }
-
- if (pos_last == pos_first || pos_last < pos_first)
- {
- const int num = 5;
-
- // "/" not found use the beginning and the end part
- begin_path = std::string(url_path, 0, num);
- end_path = std::string(url_path, url_path.size() - num - 1, num);
- }
- else
- {
- begin_path = std::string(url_path, 0, pos_first + 1);
- end_path = std::string(url_path, pos_last);
- }
- }
-
- std::string new_path = begin_path + "..." + end_path;
- zypp::Url ret(url);
-
- // use the shorter path
- ret.setPathName(new_path);
- // remove query parameters
- ret.setQueryString("");
- // remove fragmet
- ret.setFragment("");
-
- y2milestone("Using shortened URL: '%s' -> '%s'", url.asString().c_str(), ret.asString().c_str());
- return ret;
-}
-
-/** Create a Source and immediately put it into the SourceManager.
- * \return the SourceId
- * \throws Exception if Source creation fails
-*/
-std::vector<zypp::RepoInfo>::size_type
-PkgModuleFunctions::createManagedSource( const zypp::Url & url_r,
- const zypp::Pathname & path_r,
- const bool base_source,
- const std::string& type,
- const std::string &alias_r )
-{
- // parse URL
- y2milestone ("Original URL: %s, product directory: %s", url_r.asString().c_str(), path_r.asString().c_str());
-
- // #158850#c17, if the URL contains an alias, we use that
- zypp::Url url;
-
- std::string alias = removeAlias(url_r, url);
- y2milestone("Alias from URL: '%s'", alias.c_str());
-
-#warning FIXME: use base_source (base_source vs. addon) (will be probably not needed)
-
- // repository type
- zypp::repo::RepoType repotype;
- zypp::RepoManager repomanager = CreateRepoManager();
-
- if (!type.empty())
- {
- try
- {
- // do conversion from the Yast type ("YaST", "YUM", "Plaindir")
- // to libzypp type ("yast", "yum", "plaindir")
- repotype = repotype.parse(yast2zyppType(type));
- }
- catch (zypp::repo::RepoUnknownTypeException &e)
- {
- y2warning("Unknown source type '%s'", type.c_str());
- }
- }
-
- // the type is not specified or is wrong, autoprobe the type
- if (repotype == zypp::repo::RepoType::NONE)
- {
- zypp::Url probe_url(url_r);
-
- if (!path_r.asString().empty())
- {
- zypp::Pathname pth(probe_url.getPathName());
- pth /= path_r;
-
- probe_url.setPathName(pth.asString());
- }
-
- y2milestone("Probing source type: '%s'", probe_url.asString().c_str());
-
- // autoprobe type of the repository
- repotype = ProbeWithCallbacks(probe_url);
- }
-
- y2milestone("Using source type: %s", repotype.asString().c_str());
-
-
- // create source definition object
- zypp::RepoInfo repo;
-
- std::string name;
-
- // set alias and name
- if (alias.empty())
- {
- // alias not set via URL, use the passed alias or the URL path
- if (alias_r.empty())
- {
- // use the last path element in URL
- std::string url_path = url.getPathName();
-
- std::string::size_type pos_begin = url_path.rfind("/");
- std::string::size_type pos_end = std::string::npos;
-
- // ignore the trailing slash
- if (pos_begin == url_path.size() - 1)
- {
- pos_begin = url_path.rfind("/", url_path.size() - 2);
-
- if (pos_begin != std::string::npos)
- {
- pos_end = url_path.size() - pos_begin - 2;
- }
- }
- else
- {
- pos_end = url_path.size() - pos_begin - 1;
- }
-
- // ignore the found slash character
- pos_begin++;
-
- alias = std::string(url_path, pos_begin, pos_end);
-
- y2milestone("Alias from URL path: %s", alias.c_str());
-
- // fallback
- if (alias.empty())
- {
- y2milestone("URL alias is empty using 'Repository'");
- alias = "Repository";
- }
- }
- else
- {
- alias = alias_r;
- }
-
- name = alias;
- }
- else
- {
- name = alias;
- }
-
-
- y2milestone("Name of the repository: '%s'", name.c_str());
-
- // alias must be unique, add a suffix if it's already used
- alias = UniqueAlias(alias);
-
- // add read only mount option to the URL if needed
- url = addRO(url);
-
- bool autorefresh = true;
-
- std::string scheme = zypp::str::toLower(url.getScheme());
- if (scheme == "cd" || scheme == "dvd")
- {
- y2milestone("Disabling autorefresh for CD/DVD repository");
- autorefresh = false;
- }
-
- repo.setAlias(alias);
- repo.setName(name);
- repo.setType(repotype);
- repo.addBaseUrl(url);
- repo.setPath(path_r);
- repo.setEnabled(true);
- repo.setAutorefresh(autorefresh);
-
- // set metadata path (#293428)
- zypp::Pathname metadatapath = repomanager.metadataPath(repo);
- repo.setMetadataPath(metadatapath);
-
- y2milestone("Adding source '%s' (%s, dir: %s)", repo.alias().c_str(), url.asString().c_str(), path_r.asString().c_str());
- // note: exceptions should be caught by the calling code
- RefreshWithCallbacks(repo);
-
- // build cache if needed
- if (!repomanager.isCached(repo))
- {
- y2milestone("Caching source '%s'...", repo.alias().c_str());
- repomanager.buildCache(repo);
- }
-
- repos.push_back(new YRepo(repo));
-
- y2milestone("Added source '%s': '%s', enabled: %s, autorefresh: %s",
- repo.alias().c_str(),
- repo.baseUrlsBegin()->asString().c_str(),
- repo.enabled() ? "true" : "false",
- repo.autorefresh() ? "true" : "false"
- );
-
- // the source is at the end of the list
- return repos.size() - 1;
-}
-
-/****************************************************************************************
- * @builtin RepositoryAdd
- *
- * @short Register a new repository
- * @description
- * Adds a new repository to the internal structures. The repository is only registered,
- * metadata is not downloaded, use Pkg::SourceRefreshNow() for that. The metadata is also loaded
- * automatically when loading the repository content (Pkg::SourceLoad())
- *
- * @param map map with repository parameters: $[ "enabled" : boolean, "autorefresh" : boolean, "name" : string,
- * "alias" : string, "base_urls" : list<string>, "prod_dir" : string, "type" : string ]
- * @return integer Repository ID or nil on error
- **/
-YCPValue PkgModuleFunctions::RepositoryAdd(const YCPMap ¶ms)
-{
- zypp::RepoInfo repo;
-
- // turn on the repo by default
- repo.setEnabled(true);
- // enable autorefresh by default
- repo.setAutorefresh(true);
-
- if (!params->value( YCPString("enabled") ).isNull() && params->value(YCPString("enabled"))->isBoolean())
- {
- repo.setEnabled(params->value(YCPString("enabled"))->asBoolean()->value());
- }
-
- if (!params->value( YCPString("autorefresh") ).isNull() && params->value(YCPString("autorefresh"))->isBoolean())
- {
- repo.setAutorefresh(params->value(YCPString("autorefresh"))->asBoolean()->value());
- }
-
- std::string alias;
-
- if (!params->value( YCPString("alias") ).isNull() && params->value(YCPString("alias"))->isString())
- {
- alias = params->value(YCPString("alias"))->asString()->value();
- }
-
- if (alias.empty())
- {
- alias = timestamp();
-
- // the alias must be unique
- alias = UniqueAlias(alias);
- }
- else
- {
- if (aliasExists(alias))
- {
- ycperror("alias %s already exists", alias.c_str());
- return YCPVoid();
- }
- }
-
- repo.setAlias(alias);
-
- // use the first base URL as a fallback name
- std::string first_url;
-
- if (!params->value( YCPString("base_urls") ).isNull() && params->value(YCPString("base_urls"))->isList())
- {
- YCPList lst(params->value(YCPString("base_urls"))->asList());
-
- for (int index = 0; index < lst->size(); ++index)
- {
- if( ! lst->value(index)->isString() )
- {
- ycperror( "Pkg::RepositoryAdd(): entry not a string at index %d: %s", index, lst->toString().c_str());
- return YCPVoid();
- }
-
- zypp::Url url;
-
- try
- {
- url = lst->value(index)->asString()->value();
- zypp::Url url_new;
-
- std::string name = removeAlias(url, url_new);
-
- if (!name.empty())
- {
- repo.setName(name);
- url = url_new;
- }
-
- // add read only mount option to the URL if needed
- url = addRO(url);
- }
- catch(const zypp::Exception & expt)
- {
- y2error("Invalid URL: %s", expt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(expt));
- return YCPVoid();
- }
-
- if (index == 0)
- {
- first_url = url.asString();
- }
-
- repo.addBaseUrl(url);
- }
- }
- else
- {
- ycperror("Missing \"base_urls\" key in the map");
- return YCPVoid();
- }
-
- // check name parameter
- if (!params->value( YCPString("name") ).isNull() && params->value(YCPString("name"))->isString())
- {
- repo.setName(params->value(YCPString("name"))->asString()->value());
- }
- else
- {
- // if the key "name" is missing and the name hasn't been set by ?alias= in the URL
- // then use the first URL as the name
- if (repo.name().empty())
- {
- repo.setName(first_url);
- }
- }
-
- if (!params->value( YCPString("type") ).isNull() && params->value(YCPString("type"))->isString())
- {
- std::string type = yast2zyppType(params->value(YCPString("type"))->asString()->value());
-
- try
- {
- zypp::repo::RepoType repotype(type);
- repo.setType(repotype);
- }
- catch (zypp::repo::RepoUnknownTypeException &e)
- {
- ycperror("Unknown source type '%s': %s", type.c_str(), e.asString().c_str());
- _last_error.setLastError(ExceptionAsString(e));
- return YCPVoid();
- }
-
- }
-
- if (!params->value( YCPString("prod_dir") ).isNull() && params->value(YCPString("prod_dir"))->isString())
- {
- repo.setPath(params->value(YCPString("prod_dir"))->asString()->value());
- }
-
- // set metadata path (#293428)
- zypp::RepoManager repomanager = CreateRepoManager();
- zypp::Pathname metadatapath = repomanager.metadataPath(repo);
- repo.setMetadataPath(metadatapath);
-
- repos.push_back(new YRepo(repo));
-
- // the new source is at the end of the list
- return YCPInteger(repos.size() - 1);
-}
-
-/****************************************************************************************
- * @builtin SourceCacheCopyTo
- *
- * @short Copy cache data of all installation sources to the target
- * @description
- * Copy cache data of all installation sources to the target located below 'dir'.
- * To be called at end of initial installation.
- *
- * @param string dir Root directory of target.
- * @return boolean true on success
- **/
-YCPValue
-PkgModuleFunctions::SourceCacheCopyTo (const YCPString& dir)
-{
- // error message (followed by detailed description)
- const std::string msg = _("Error: Cannot copy the cache to the target directory\n");
-
- std::string d = dir->value();
- y2milestone("Copying source cache to '%s'...", d.c_str());
-
- if (d.empty())
- {
- y2error("Empty parameter in Pkg::SourceCacheCopyTo()!");
- return YCPBoolean(false);
- }
-
- std::string target = d + "/var/cache";
-
- // create the target dir
- const char* argv[] =
- {
- "mkdir",
- // create parent dir
- "-p",
- // finish parameter list
- "--",
- // target
- target.c_str(),
- NULL
- };
-
- // discard stderr, no pty, stderr_fd = -1, use the default locale
- zypp::ExternalProgram prog(argv, zypp::ExternalProgram::Discard_Stderr, false, -1, true);
-
- int code = prog.close();
-
- if (code)
- {
- // error message (followed by directory name)
- _last_error.setLastError(msg + _("Cannot create directory ") + target);
- y2error("Cannot create target directory %s", target.c_str());
- return YCPBoolean(false);
- }
-
- // copy /var/cache/zypp to the target system
- const char* argv2[] =
- {
- "cp",
- // preserve time stamps
- "-a",
- // recursive
- "-r",
- // finish parameter list
- "--",
- // source
- "/var/cache/zypp",
- // target
- target.c_str(),
- NULL
- };
-
- // discard stderr, no pty, stderr_fd = -1, use the default locale
- zypp::ExternalProgram prog2(argv2, zypp::ExternalProgram::Discard_Stderr, false, -1, true);
-
- int code2 = prog2.close();
-
- if (code2)
- {
- // error message
- _last_error.setLastError(msg + _("Copying failed"));
- y2error("Cannot copy /var/cache/zypp to %s", d.c_str());
- }
-
- return YCPBoolean(!code2);
-}
-
-/****************************************************************************************
- * @builtin SourceScan
- * @short Scan a Source Media
- * @description
- * Load all InstSrces found at media_url, i.e. all sources mentioned in /media.1/products.
- * If no /media.1/products is available, InstSrc is expected to be located directly
- * below media_url (product_dir: /).
- *
- * If a product_dir is provided, only the InstSrc located at media_url/product_dir is loaded.
- *
- * In contrary to @ref SourceCreate, InstSrces are loaded into the InstSrcManager,
- * but not enabled (packages and selections are not provided to the PackageManager),
- * and the SrcIds of <b>all</b> InstSrces found are returned.
- *
- * @param string url The media to scan.
- * @optarg string product_dir Restrict scan to a certain InstSrc located in media_url/product_dir.
- *
- * @return list<integer> list of SrcIds (integer).
- **/
-YCPValue
-PkgModuleFunctions::SourceScan (const YCPString& media, const YCPString& pd)
-{
- zypp::Url url;
-
- try {
- url = zypp::Url(media->value ());
- }
- catch(const zypp::Exception & expt )
- {
- y2error ("Invalid URL: %s", expt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(expt));
- return YCPList();
- }
-
- zypp::Pathname pn(pd->value ());
-
- YCPList ids;
- std::vector<zypp::RepoInfo>::size_type id;
-
- if ( pd->value().empty() ) {
-
- // scan all sources
- zypp::MediaProductSet products;
-
- try
- {
- y2milestone("Scanning products in %s ...", url.asString().c_str());
- ScanProductsWithCallBacks(url);
- products = available_products;
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("Scanning products for '%s' has failed"
- , url.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- return ids;
- }
-
- if( products.empty() )
- {
- // no products found, use the base URL instead
- zypp::MediaProductEntry entry;
- products.insert(entry);
- }
-
- for( zypp::MediaProductSet::const_iterator it = products.begin();
- it != products.end() ; ++it )
- {
- try
- {
- y2milestone("Using product %s in directory %s", it->_name.c_str(), it->_dir.c_str());
- id = createManagedSource(url, it->_dir, false, "", it->_name);
- ids->add( YCPInteger(id) );
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("SourceScan for '%s' product '%s' has failed"
- , url.asString().c_str(), pn.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- }
- }
- } else {
- y2debug("Creating source...");
-
- try
- {
- id = createManagedSource(url, pn, false, "", "");
- ids->add( YCPInteger(id) );
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("SourceScan for '%s' product '%s' has failed"
- , url.asString().c_str(), pn.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- }
- }
-
- y2milestone("Found sources: %s", ids->toString().c_str() );
-
- return ids;
-}
-
-/****************************************************************************************
- * @builtin SourceCreate
- *
- * @short Create a Source
- * @description
- * Load and enable all InstSrces found at media_url, i.e. all sources mentioned in /media.1/products.
- * If no /media.1/products is available, InstSrc is expected to be located directly below
- * media_url (product_dir: /).
- *
- * If a product_dir is provided, only the InstSrc located at media_url/product_dir is loaded
- * and enabled.
- *
- * @param string url The media to scan.
- * @optarg string product_dir Restrict scan to a certain InstSrc located in media_url/product_dir.
- *
- * @return integer The source_id of the first InstSrc found on the media.
- **/
-YCPValue
-PkgModuleFunctions::SourceCreate (const YCPString& media, const YCPString& pd)
-{
- // not base product, autoprobe source type
- return SourceCreateEx (media, pd, false, YCPString(""));
-}
-
-YCPValue
-PkgModuleFunctions::SourceCreateBase (const YCPString& media, const YCPString& pd)
-{
- // base product, autoprobe source type
- return SourceCreateEx (media, pd, true, YCPString(""));
-}
-
-/**
- * @builtin SourceCreateType
- * @short Create source of required type
- * @description
- * Create a source without autoprobing the source type. This builtin should be used only for "Plaindir" sources, because Plaindir sources are not automatically probed in SourceCreate() builtin.
- * @param media URL of the source
- * @param pd product directory (if empty the products will be searched)
- * @param type type of the source ("YaST", "YUM" or "Plaindir")
-*/
-
-YCPValue
-PkgModuleFunctions::SourceCreateType (const YCPString& media, const YCPString& pd, const YCPString& type)
-{
- // not base product, autoprobe source type
- return SourceCreateEx (media, pd, false, type);
-}
-
-YCPValue
-PkgModuleFunctions::SourceCreateEx (const YCPString& media, const YCPString& pd, bool base, const YCPString& source_type)
-{
- y2debug("Creating source...");
-
- zypp::Pathname pn(pd->value ());
-
- zypp::Url url;
-
- try {
- url = zypp::Url(media->value ());
- }
- catch(const zypp::Exception & expt )
- {
- y2error ("Invalid URL: %s", expt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(expt));
- return YCPInteger (-1LL);
- }
-
-
- YCPList ids;
- std::vector<zypp::RepoInfo>::size_type ret = -1;
-
- const std::string type = source_type->value();
-
- if ( pd->value().empty() ) {
- // scan all sources
- zypp::MediaProductSet products;
-
- try {
- ScanProductsWithCallBacks(url);
- products = available_products;
- }
- catch ( const zypp::Exception& excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error( "Cannot read the product list from the media" );
- return YCPInteger(-1LL);
- }
-
- if( products.empty() )
- {
- // no products found, use the base URL instead
- zypp::MediaProductEntry entry ;
- products.insert( entry );
- }
-
- for( zypp::MediaProductSet::const_iterator it = products.begin();
- it != products.end() ; ++it )
- {
- try
- {
- std::vector<zypp::RepoInfo>::size_type id = createManagedSource(url, it->_dir, base, type, it->_name);
- YRepo_Ptr repo = logFindRepository(id);
-
- LoadResolvablesFrom(repo->repoInfo());
-
- // return the id of the first product
- if ( it == products.begin() )
- ret = id;
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("SourceCreate for '%s' product '%s' has failed"
- , url.asString().c_str(), pn.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- return YCPInteger(-1LL);
- }
- }
- } else {
- y2debug("Creating source...");
-
- try
- {
- ret = createManagedSource(url, pn, base, type, "");
-
- YRepo_Ptr repo = logFindRepository(ret);
- repo->repoInfo().setEnabled(true);
-
- LoadResolvablesFrom(repo->repoInfo());
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("SourceCreate for '%s' product '%s' has failed"
- , url.asString().c_str(), pn.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- }
- }
-
- PkgFreshen();
- return YCPInteger(repos.size() - 1);
-}
-
-
-/****************************************************************************************
- * @builtin SourceSetEnabled
- *
- * @short Set the default activation state of an InsrSrc.
- * @param integer SrcId Specifies the InstSrc.
- * @param boolean enabled Default activation state of source.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceSetEnabled (const YCPInteger& id, const YCPBoolean& e)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- // no change required
- bool enable = e->value();
- if ((enable && repo->repoInfo().enabled())
- || (!enable && !repo->repoInfo().enabled()))
- return YCPBoolean(true);
-
- bool success = true;
-
- try
- {
- repo->repoInfo().setEnabled(enable);
-
- // add/remove resolvables
- if (enable)
- {
- // load resolvables only when they are missing
- if (!AnyResolvableFrom(repo->repoInfo().alias()))
- {
- success = LoadResolvablesFrom(repo->repoInfo());
- }
- }
- else
- {
- // the source has been disabled, remove resolvables from the pool
- RemoveResolvablesFrom(repo->repoInfo().alias());
- }
-
- PkgFreshen();
- }
- catch (const zypp::Exception& excpt)
- {
- std::string alias = repo->repoInfo().alias();
- y2error ("Error for '%s': %s", alias.c_str(), excpt.asString().c_str());
- _last_error.setLastError(alias + ": " + ExceptionAsString(excpt));
- success = false;
- }
-
- return YCPBoolean(success);
-}
-
-/****************************************************************************************
- * @builtin SourceSetAutorefresh
- *
- * @short Set whether this source should automaticaly refresh it's
- * meta data when it gets enabled. (default true, if not CD/DVD)
- * @param integer SrcId Specifies the InstSrc.
- * @param boolean enabled Whether autorefresh should be turned on or off.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceSetAutorefresh (const YCPInteger& id, const YCPBoolean& e)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- repo->repoInfo().setAutorefresh(e->value());
-
- return YCPBoolean( true );
-}
-
-/****************************************************************************************
- * @builtin SourceFinish
- * @short Disable an Installation Source
- * @param integer SrcId Specifies the InstSrc.
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceFinish (const YCPInteger& id)
-{
- return SourceSetEnabled(id, false);
-}
-
-/****************************************************************************************
- * @builtin SourceRefreshNow
- * @short Attempt to immediately refresh a Source
- * @description
- * The InsrSrc will be encouraged to check and refresh all metadata
- * cached on disk.
- *
- * @param integer SrcId Specifies the InstSrc.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceRefreshNow (const YCPInteger& id)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- try
- {
- zypp::RepoManager repomanager = CreateRepoManager();
- y2milestone("Refreshing metadata '%s'", repo->repoInfo().alias().c_str());
- RefreshWithCallbacks(repo->repoInfo());
-
- y2milestone("Caching source '%s'...", repo->repoInfo().alias().c_str());
- repomanager.buildCache(repo->repoInfo());
- }
- catch ( const zypp::Exception & expt )
- {
- y2error ("Error while refreshing the source: %s", expt.asString().c_str());
- _last_error.setLastError(repo->repoInfo().alias() + ": " + ExceptionAsString(expt));
- return YCPBoolean(false);
- }
-
- return YCPBoolean( true );
-}
-
-/****************************************************************************************
- * @builtin SourceDelete
- * @short Delete a Source
- * @description
- * Delete an InsrSrc. The InsrSrc together with all metadata cached on disk
- * is removed. The SrcId passed becomes invalid (other SrcIds stay valid).
- *
- * @param integer SrcId Specifies the InstSrc.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceDelete (const YCPInteger& id)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- bool success = true;
-
- try
- {
- // the resolvables cannot be used anymore, remove them
- RemoveResolvablesFrom(repo->repoInfo().alias());
-
- // update 'repos'
- repo->setDeleted();
-
- PkgFreshen();
- }
- catch (const zypp::Exception& excpt)
- {
- std::string alias = repo->repoInfo().alias();
- y2error ("Error for '%s': %s", alias.c_str(), excpt.asString().c_str());
- _last_error.setLastError(alias + ": " + ExceptionAsString(excpt));
- success = false;
- }
-
- return YCPBoolean(success);
-}
-
-/****************************************************************************************
- * @builtin SourceEditGet
- *
- * @short Get state of Sources
- * @description
- * Return a list of states for all known InstSources sorted according to the
- * source priority (highest first). A source state is a map:
- * $[
- * "SrcId" : YCPInteger,
- * "enabled" : YCPBoolean
- * "autorefresh": YCPBoolean
- * ];
- *
- * @return list<map> list of source states (map)
- **/
-YCPValue
-PkgModuleFunctions::SourceEditGet ()
-{
- YCPList ret;
-
- unsigned long index = 0;
- for( std::vector<YRepo_Ptr>::const_iterator it = repos.begin(); it != repos.end(); ++it, ++index)
- {
- if (!(*it)->isDeleted())
- {
- YCPMap src_map;
-
- src_map->add(YCPString("SrcId"), YCPInteger(index));
- // Note: enabled() is tribool
- src_map->add(YCPString("enabled"), YCPBoolean((*it)->repoInfo().enabled()));
- // Note: autorefresh() is tribool
- src_map->add(YCPString("autorefresh"), YCPBoolean((*it)->repoInfo().autorefresh()));
- src_map->add(YCPString("name"), YCPString((*it)->repoInfo().name()));
-
- ret->add(src_map);
- }
- }
-
- return ret;
-}
-
-/****************************************************************************************
- * @builtin SourceEditSet
- *
- * @short Configure properties of installation sources
- * @description
- * Set states of installation sources. Note: Enabling/disabling a source does not
- * (un)load the packages from the source! Use SourceSetEnabled() if you need to refresh
- * the packages in the pool.
- *
- * @param list source_states List of source states. Same format as returned by
- * @see SourceEditGet.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceEditSet (const YCPList& states)
-{
- bool error = false;
-
- for (int index = 0; index < states->size(); index++ )
- {
- if( ! states->value(index)->isMap() )
- {
- ycperror( "Pkg::SourceEditSet, entry not a map at index %d", index);
- error = true;
- continue;
- }
-
- YCPMap descr = states->value(index)->asMap();
-
- if (descr->value( YCPString("SrcId") ).isNull() || !descr->value(YCPString("SrcId"))->isInteger())
- {
- ycperror( "Pkg::SourceEditSet, SrcId not defined for a source description at index %d", index);
- error = true;
- continue;
- }
-
- std::vector<YRepo_Ptr>::size_type id = descr->value( YCPString("SrcId") )->asInteger()->value();
-
- YRepo_Ptr repo = logFindRepository(id);
- if (!repo)
- {
- ycperror( "Pkg::SourceEditSet, source %d not found", index);
- error = true;
- continue;
- }
-
- // now, we have the source
- if( ! descr->value( YCPString("enabled")).isNull() && descr->value(YCPString("enabled"))->isBoolean ())
- {
- bool enable = descr->value(YCPString("enabled"))->asBoolean ()->value();
-
- if (repo->repoInfo().enabled() != enable)
- {
- ycpwarning("Pkg::SourceEditSet() does not refresh the pool (src: %zd, state: %s)", id, enable ? "disabled -> enabled" : "enabled -> disabled");
- }
-
- y2debug("set enabled: %d", enable);
- repo->repoInfo().setEnabled(enable);
- }
-
- if( !descr->value(YCPString("autorefresh")).isNull() && descr->value(YCPString("autorefresh"))->isBoolean ())
- {
- bool autorefresh = descr->value(YCPString("autorefresh"))->asBoolean()->value();
- y2debug("set autorefresh: %d", autorefresh);
- repo->repoInfo().setAutorefresh( autorefresh );
- }
-
- if( !descr->value(YCPString("name")).isNull() && descr->value(YCPString("name"))->isString())
- {
- // rename the source
- y2debug("set name: %s", descr->value(YCPString("name"))->asString()->value().c_str());
- repo->repoInfo().setName(descr->value(YCPString("name"))->asString()->value());
- }
-
-#warning SourceEditSet ordering not implemented yet
- }
-
- PkgFreshen();
- return YCPBoolean( !error );
-}
-
-/////////////////////////////////////////////////////////////////////////////////////////
-//
-// DEPRECATED
-//
-/////////////////////////////////////////////////////////////////////////////////////////
-
-/****************************************************************************************
- * Pkg::SourceRaisePriority (integer SrcId) -> bool
- *
- * Raise priority of source.
- *
- * @param SrcId Specifies the InstSrc.
- *
- * @return bool
- **/
-YCPValue
-PkgModuleFunctions::SourceRaisePriority (const YCPInteger& id)
-{
-#warning SourceRaisePriority is not implemented
- y2warning("SourceRaisePriority is NOT implemented");
-/* zypp::Source_Ref src;
-
- try {
- src = logFindRepository(id->value());
- }
- catch (const zypp::Exception& excpt)
- {
- return YCPBoolean(false);
- }
-
- // raise priority by one
- src.setPriority(src.priority() + 1);
-*/
-
- return YCPBoolean( true );
-
-}
-
-/****************************************************************************************
- * Pkg::SourceLowerPriority (integer SrcId) -> void
- *
- * Lower priority of source.
- *
- * @param SrcId Specifies the InstSrc.
- *
- * @return bool
- */
-YCPValue
-PkgModuleFunctions::SourceLowerPriority (const YCPInteger& id)
-{
-#warning SourceLowerPriority is not implemented
- y2warning("SourceLowerPriority is NOT implemented");
-/*
- zypp::Source_Ref src;
-
- try {
- src = logFindRepository(id->value());
- }
- catch (const zypp::Exception& excpt)
- {
- return YCPBoolean(false);
- }
-
- // lower priority by one
- src.setPriority(src.priority() - 1);
-*/
- return YCPBoolean( true );
-}
-
-/****************************************************************************************
- * Pkg::SourceSaveRanks () -> boolean
- *
- * @short Obsoleted function, do not use
- * @return boolean true
- **/
-YCPValue
-PkgModuleFunctions::SourceSaveRanks ()
-{
- y2error( "SourceSaveRanks not implemented" );
-
- return YCPBoolean( true );
-}
-
-/****************************************************************************************
- * @builtin SourceMoveDownloadArea
- *
- * @short Move download area of CURL-based sources to specified directory
- * @param path specifies the path to move the download area to
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceMoveDownloadArea (const YCPString & path)
-{
- try
- {
- y2milestone("Moving download area of all sources to %s", path->value().c_str());
- zypp::media::MediaManager manager;
- manager.setAttachPrefix(path->value());
- }
- catch (zypp::Exception & excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error("Pkg::SourceMoveDownloadArea has failed: %s", excpt.msg().c_str());
- return YCPBoolean(false);
- }
-
- y2milestone( "Download areas moved");
-
- return YCPBoolean(true);
-}
-
-/*
- * A helper function - remove all resolvables from the repository from the pool
- */
-void PkgModuleFunctions::RemoveResolvablesFrom(const std::string &alias)
-{
- // remove the resolvables if they have been loaded
- // FIXME: can be implemented better? we need a ResStore object for removing,
- // which means search for a resolvable in the pool and get the Repository
- // object which can be asked for all resolvables in it
- for (zypp::ResPool::const_iterator it = zypp_ptr()->pool().begin()
- ; it != zypp_ptr()->pool().end()
- ; ++it)
- {
- if (it->resolvable()->repository().info().alias() == alias)
- {
- y2milestone("Removing all resolvables from '%s' from the pool...", alias.c_str());
- zypp_ptr()->removeResolvables(it->resolvable()->repository().resolvables());
- break;
- }
- }
-}
-
-/*
- * A helper function - is there any resolvable from the repository in the pool?
- */
-bool PkgModuleFunctions::AnyResolvableFrom(const std::string &alias)
-{
- for (zypp::ResPool::const_iterator it = zypp_ptr()->pool().begin()
- ; it != zypp_ptr()->pool().end()
- ; ++it)
- {
- if (it->resolvable()->repository().info().alias() == alias)
- {
- return true;
- }
- }
-
- return false;
-}
-
-/*
- * A helper function - load resolvable from the repository into the pool
- * Warning: Use AnyResolvableFrom() method for checing if the resolvables might be already loaded
- */
-bool PkgModuleFunctions::LoadResolvablesFrom(const zypp::RepoInfo &repoinfo)
-{
- bool success = true;
- unsigned int size_start = zypp_ptr()->pool().size();
- y2milestone("Loading resolvables from '%s', pool size at start: %d", repoinfo.alias().c_str(), size_start);
-
- try
- {
- zypp::RepoManager repomanager = CreateRepoManager();
-
- // build cache if needed
- if (!repomanager.isCached(repoinfo))
- {
- zypp::RepoStatus raw_metadata_status = repomanager.metadataStatus(repoinfo);
- if (raw_metadata_status.empty())
- {
- y2milestone("Missing metadata for source '%s', downloading...", repoinfo.alias().c_str());
- RefreshWithCallbacks(repoinfo);
- }
-
- y2milestone("Caching source '%s'...", repoinfo.alias().c_str());
- repomanager.buildCache(repoinfo);
- }
-
- zypp::Repository repository = repomanager.createFromCache(repoinfo);
- const zypp::ResStore &store = repository.resolvables();
-
- // load resolvables
- zypp_ptr()->addResolvables(store);
-
- y2milestone("Loaded %zd resolvables", store.size());
- }
- catch(const zypp::repo::RepoNotCachedException &excpt )
- {
- std::string alias = repoinfo.alias();
- y2error ("Resolvables from '%s' havn't been loaded: %s", alias.c_str(), excpt.asString().c_str());
- _last_error.setLastError("'" + alias + "': " + ExceptionAsString(excpt));
- success = false;
-
- // FIXME ??
- /*
- // disable the source
- y2error("Disabling source %s", url.c_str());
- repo->disable();
- */
- }
- catch (const zypp::Exception& excpt)
- {
- std::string alias = repoinfo.alias();
- y2internal("Error: Loading resolvables failed: %s", ExceptionAsString(excpt).c_str());
- _last_error.setLastError("'" + alias + "': " + ExceptionAsString(excpt));
- success = false;
- }
-
- unsigned int size_end = zypp_ptr()->pool().size();
- y2milestone("Pool size at end: %d (loaded %d resolvables)", size_end, size_end - size_start);
- return success;
-}
-
-/****************************************************************************************
- * @builtin RepositoryProbe
- *
- * @short Probe type of the repository
- * @param url specifies the path to the repository
- * @param prod_dir product directory (if empty the url is probed directly)
- * @return string repository type ("NONE" if type could be determined, nil if an error occurred (e.g. resolving the hostname)
- **/
-YCPValue PkgModuleFunctions::RepositoryProbe(const YCPString& url, const YCPString& prod_dir)
-{
- y2milestone("Probing repository type: '%s'...", url->value().c_str());
- zypp::RepoManager repomanager = CreateRepoManager();
- std::string ret;
-
- try
- {
- zypp::Url probe_url(url->value());
-
- // add the product directory
- std::string prod = prod_dir->value();
-
- if (!prod.empty())
- {
- // add "/" at the begining if it's missing
- if (std::string(prod, 0, 1) != "/")
- {
- prod = "/" + prod;
- }
-
- // merge the URL path and the product path
- std::string path = probe_url.getPathName();
- path += prod;
-
- y2milestone("Using probing path: %s", path.c_str());
- probe_url.setPathName(path);
- }
-
- // add "ro" mount option
- probe_url = addRO(probe_url);
-
- // autoprobe type of the repository
- zypp::repo::RepoType repotype = ProbeWithCallbacks(probe_url);
-
- ret = zypp2yastType(repotype.asString());
- y2milestone("Detected type: '%s'...", ret.c_str());
- }
- catch (const zypp::Exception& excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error( "Cannot detect the repository type" );
- return YCPVoid();
- }
-
- return YCPString(ret);
-}
-
-/****************************************************************************************
- * @builtin RepositoryScan
- *
- * @short Scan available products in the repository
- * @param url specifies the path to the repository
- * @return list<list<string>> list of the products: [ [ <product_name_1> <directory_1> ], ...]
- **/
-YCPValue PkgModuleFunctions::RepositoryScan(const YCPString& url)
-{
- zypp::MediaProductSet products;
-
- try
- {
- zypp::Url baseurl(url->value());
-
- baseurl = addRO(baseurl);
-
- ScanProductsWithCallBacks(baseurl);
- products = available_products;
- }
- catch ( const zypp::Exception& excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error( "Cannot read the product list from the media" );
- return YCPList();
- }
-
- YCPList ret;
-
- for( zypp::MediaProductSet::const_iterator it = products.begin();
- it != products.end() ; ++it )
- {
- YCPList prod;
-
- // add product directory
- prod.add(YCPString(it->_name));
- // add product name
- prod.add(YCPString(it->_dir.asString()));
-
- ret.add(prod);
- }
-
- y2milestone("Found products: %s", ret->toString().c_str());
-
- return ret;
-}
-
-// convert libzypp type to yast strings ("YaST", "YUM" or "Plaindir")
-std::string PkgModuleFunctions::zypp2yastType(const std::string &type)
-{
- std::string ret(type);
-
- if (type_conversion_table.empty())
- {
- // initialize the conversion map
- type_conversion_table["rpm-md"] = "YUM";
- type_conversion_table["yast2"] = "YaST";
- type_conversion_table["plaindir"] = "Plaindir";
- type_conversion_table["NONE"] = "NONE";
- }
-
- std::map<std::string,std::string>::const_iterator it = type_conversion_table.find(type);
-
- // found in the conversion table
- if (it != type_conversion_table.end())
- {
- ret = it->second;
- }
- else
- {
- y2error("Cannot convert type '%s'", type.c_str());
- }
-
- return ret;
-}
-
-std::string PkgModuleFunctions::yast2zyppType(const std::string &type)
-{
- // do conversion from the Yast type ("YaST", "YUM", "Plaindir")
- // to libzypp type ("yast", "yum", "plaindir")
- // we can simply use toLower instead of a conversion table
- // in this case
- return zypp::str::toLower(type);
-}
-
Copied: trunk/pkg-bindings/src/Source_Misc.cc (from r42708, trunk/pkg-bindings/src/Source.cc)
URL: http://svn.opensuse.org/viewcvs/yast/trunk/pkg-bindings/src/Source_Misc.cc?…
==============================================================================
--- trunk/pkg-bindings/src/Source.cc (original)
+++ trunk/pkg-bindings/src/Source_Misc.cc Thu Dec 6 07:56:58 2007
@@ -1,251 +1,37 @@
-/*---------------------------------------------------------------------\
-| |
-| __ __ ____ _____ ____ |
-| \ \ / /_ _/ ___|_ _|___ \ |
-| \ V / _` \___ \ | | __) | |
-| | | (_| |___) || | / __/ |
-| |_|\__,_|____/ |_| |_____| |
-| |
-| core system |
-| (C) SuSE GmbH |
-\----------------------------------------------------------------------/
-
- File: PkgModuleFunctionsSource.cc
-
- Author: Klaus Kaempf <kkaempf(a)suse.de>
- Maintainer: Klaus Kaempf <kkaempf(a)suse.de>
-
- Summary: Access to Installation Sources
- Namespace: Pkg
- Purpose: Access to InstSrc
- Handles source related Pkg::function (list_of_arguments) calls
- from WFMInterpreter.
-/-*/
-//#include <unistd.h>
-//#include <sys/statvfs.h>
-
-#include <iostream>
+/* ------------------------------------------------------------------------------
+ * Copyright (c) 2007 Novell, Inc. All Rights Reserved.
+ *
+ *
+ * This program is free software; you can redistribute it and/or modify it under
+ * the terms of version 2 of the GNU General Public License as published by the
+ * Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+ * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along with
+ * this program; if not, contact Novell, Inc.
+ *
+ * To contact Novell about this file by physical or electronic mail, you may find
+ * current contact information at www.novell.com.
+ * ------------------------------------------------------------------------------
+ */
-#include <ycpTools.h>
-#include <PkgModule.h>
-#include <PkgModuleFunctions.h>
+/*
+ File: $Id:$
+ Author: Ladislav Slezák <lslezak(a)novell.com>
+ Summary: Generic functions for accessing repositories from Yast
+*/
#include <Callbacks.h>
#include <Callbacks.YCP.h>
-#include <zypp/Product.h>
-#include <zypp/media/MediaManager.h>
-#include <zypp/media/Mount.h>
-#include <zypp/Pathname.h>
-
-#include <zypp/RepoInfo.h>
-#include <zypp/RepoManager.h>
-#include <zypp/Fetcher.h>
-#include <zypp/repo/RepoType.h>
-#include <zypp/MediaProducts.h>
-#include <zypp/ExternalProgram.h>
-#include <zypp/ProgressData.h>
+#include <PkgModule.h>
+#include <PkgModuleFunctions.h>
#include <sstream> // ostringstream
-#include <PkgProgress.h>
-
-/*
- Textdomain "pkg-bindings"
-*/
-
-// scanned available products
-// hack: zypp/MediaProducts.h cannot be included in PkgModuleFunctions.h
-zypp::MediaProductSet available_products;
-
-// this method should be used instead of zypp::productsInMedia()
-// it initializes the download callbacks
-void PkgModuleFunctions::ScanProductsWithCallBacks(const zypp::Url &url)
-{
- CallInitDownload(std::string(_("Scanning products in ") + url.asString()));
-
- extern ZyppRecipients::MediaChangeSensitivity _silent_probing;
- // remember the current value
- ZyppRecipients::MediaChangeSensitivity _silent_probing_old = _silent_probing;
-
- // disable media change callback for optional file
- _silent_probing = ZyppRecipients::MEDIA_CHANGE_DISABLE;
-
- y2milestone("Scanning products in %s ...", url.asString().c_str());
-
- try
- {
- available_products.clear();
- zypp::productsInMedia(url, available_products);
- }
- catch(...)
- {
- // call the final event even in case of exception
- CallDestDownload();
-
- // restore the probing flag
- _silent_probing = _silent_probing_old;
-
- // rethrow the execption
- throw;
- }
-
- CallDestDownload();
-
- // restore the probing flag
- _silent_probing = _silent_probing_old;
-}
-
-void PkgModuleFunctions::CallSourceReportStart(const std::string &text)
-{
- // get the YCP callback handler
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_SourceReportStart);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- // add parameters
- ycp_handler->appendParameter( YCPInteger(0LL) );
- ycp_handler->appendParameter( YCPString("") );
- ycp_handler->appendParameter( YCPString(text) );
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-
-void PkgModuleFunctions::CallSourceReportEnd(const std::string &text)
-{
- // get the YCP callback handler for end event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_SourceReportEnd);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- // add parameters
- ycp_handler->appendParameter( YCPInteger(0LL) );
- ycp_handler->appendParameter( YCPString("") );
- ycp_handler->appendParameter( YCPString(text) );
- ycp_handler->appendParameter( YCPString("NO_ERROR") );
- ycp_handler->appendParameter( YCPString("") );
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-
-void PkgModuleFunctions::CallSourceReportInit()
-{
- // get the YCP callback handler for init event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_SourceReportInit);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-
-void PkgModuleFunctions::CallSourceReportDestroy()
-{
- // get the YCP callback handler for destroy event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_SourceReportDestroy);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-
-void PkgModuleFunctions::CallInitDownload(const std::string &task)
-{
- // get the YCP callback handler for destroy event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_InitDownload);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- ycp_handler->appendParameter(YCPString(task));
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-
-void PkgModuleFunctions::CallDestDownload()
-{
- // get the YCP callback handler for destroy event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_DestDownload);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-
-// this method should be used instead of RepoManager::refreshMetadata()
-void PkgModuleFunctions::RefreshWithCallbacks(const zypp::RepoInfo &repo)
-{
- CallInitDownload(std::string(_("Refreshing repository ") + repo.alias()));
-
- try
- {
- zypp::RepoManager repomanager = CreateRepoManager();
- repomanager.refreshMetadata(repo);
- }
- catch(...)
- {
- // call the final event even in case of exception
- CallDestDownload();
- // rethrow the execption
- throw;
- }
-
- CallDestDownload();
-}
-
-// this method should be used instead of RepoManager::probe()
-zypp::repo::RepoType PkgModuleFunctions::ProbeWithCallbacks(const zypp::Url &url)
-{
- CallInitDownload(std::string(_("Probing repository ") + url.asString()));
-
- zypp::repo::RepoType repotype;
-
- extern ZyppRecipients::MediaChangeSensitivity _silent_probing;
- // remember the current value
- ZyppRecipients::MediaChangeSensitivity _silent_probing_old = _silent_probing;
-
- // disable media change callback for optional file
- _silent_probing = ZyppRecipients::MEDIA_CHANGE_DISABLE;
-
- try
- {
- // probe type of the repository
- zypp::RepoManager repomanager = CreateRepoManager();
- repotype = repomanager.probe(url);
- }
- catch(...)
- {
- // call the final event even in case of exception
- CallDestDownload();
-
- // restore the probing flag
- _silent_probing = _silent_probing_old;
-
- // rethrow the execption
- throw;
- }
-
- CallDestDownload();
-
- // restore the probing flag
- _silent_probing = _silent_probing_old;
-
- return repotype;
-}
-
/**
* Logging helper:
* call zypp::SourceManager::sourceManager()->findSource
@@ -310,2631 +96,124 @@
return false;
}
-/****************************************************************************************
- * @builtin SourceSetRamCache
- * @short Obsoleted function, do not use
- * @param boolean
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceSetRamCache (const YCPBoolean& a)
+// convert libzypp type to yast strings ("YaST", "YUM" or "Plaindir")
+std::string PkgModuleFunctions::zypp2yastType(const std::string &type)
{
- y2warning( "Pkg::SourceSetRamCache is obsolete and does nothing");
- return YCPBoolean( true );
-}
-
+ std::string ret(type);
-/****************************************************************************************
- * @builtin SourceRestore
- *
- * @short Restore the sources from the persistent store
- * @description
- * Make sure the Source Manager is up and knows all available installation sources.
- * It's safe to call this multiple times, and once the installation sources are
- * actually enabled, it's even cheap
- *
- * @return boolean True on success
- **/
-YCPValue
-PkgModuleFunctions::SourceRestore()
-{
- if (repos.size() > 0)
+ if (type_conversion_table.empty())
{
- y2warning("Number of registered repositories: %zd, skipping repository load!", repos.size());
- return YCPBoolean(true);
+ // initialize the conversion map
+ type_conversion_table["rpm-md"] = "YUM";
+ type_conversion_table["yast2"] = "YaST";
+ type_conversion_table["plaindir"] = "Plaindir";
+ type_conversion_table["NONE"] = "NONE";
}
- bool success = true;
+ std::map<std::string,std::string>::const_iterator it = type_conversion_table.find(type);
- try
+ // found in the conversion table
+ if (it != type_conversion_table.end())
{
- zypp::RepoManager repomanager = CreateRepoManager();
- std::list<zypp::RepoInfo> reps = repomanager.knownRepositories();
-
- repos.clear();
- for (std::list<zypp::RepoInfo>::iterator it = reps.begin();
- it != reps.end(); ++it)
- {
- repos.push_back(new YRepo(*it));
- }
+ ret = it->second;
}
- catch (const zypp::Exception& excpt)
+ else
{
- // FIXME: assuming the sources are already initialized
- y2error ("Error in SourceRestore: %s", excpt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- success = false;
+ y2error("Cannot convert type '%s'", type.c_str());
}
- return YCPBoolean(success);
+ return ret;
}
-/****************************************************************************************
- * @builtin SourceGetBrokenSources
- *
- * @short Return list of broken sources (sources which failed to restore)
- * @description
- * Get list of all sources which could not have been restored.
- * @return list<string> list of aliases (product names or URLs)
- **/
-YCPValue PkgModuleFunctions::SourceGetBrokenSources()
+std::string PkgModuleFunctions::yast2zyppType(const std::string &type)
{
- y2warning("Pkg::SourceGetBrokenSources() is obsoleted, it's not needed anymore.");
- return YCPList();
+ // do conversion from the Yast type ("YaST", "YUM", "Plaindir")
+ // to libzypp type ("yast", "yum", "plaindir")
+ // we can simply use toLower instead of a conversion table
+ // in this case
+ return zypp::str::toLower(type);
}
-bool PkgModuleFunctions::SourceLoadReceiver(const zypp::ProgressData &progress)
+std::string PkgModuleFunctions::UniqueAlias(const std::string &alias)
{
- y2milestone("Source Load receiver: %lld (%lld%%)", progress.val(), progress.reportValue());
-
- // get the YCP callback handler for destroy event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_ProcessProgress);
+ // make a copy
+ std::string ret = alias;
- // is the callback registered?
- if (ycp_handler != NULL)
+ unsigned int id = 0;
+ while(aliasExists(ret))
{
- ycp_handler->appendParameter(YCPInteger(progress.reportValue()));
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-
- return true;
-}
-
-/****************************************************************************************
- * @builtin SourceLoad
- *
- * @short Load resolvables from the installation sources
- * @description
- * Refresh the pool - Add/remove resolvables from the enabled/disabled sources.
- * @return boolean True on success
- **/
-YCPValue
-PkgModuleFunctions::SourceLoad()
-{
- std::list<std::string> stages;
- stages.push_back("Refresh Sources");
- stages.push_back("Rebuild Cache");
- stages.push_back("Load Data");
-
- PkgProgress pkgprogress(_callbackHandler);
+ y2milestone("Alias %s already found: %lld", ret.c_str(), logFindAlias(ret));
- // 3 steps per repository (download, cache rebuild, load resolvables)
- pkgprogress.Start("Loading the Package Manager...", stages, "help");
+ // the alias already exists - add a counter
+ std::ostringstream ostr;
+ ostr << alias << "_" << id;
- YCPValue ret = SourceLoadImpl(pkgprogress);
+ ret = ostr.str();
- pkgprogress.Done();
+ y2milestone("Using alias %s", ret.c_str());
+ ++id;
+ }
return ret;
}
-
-/****************************************************************************************
- * @builtin SourceLoad
- *
- * @short Load resolvables from the installation sources
- * @description
- * Refresh the pool - Add/remove resolvables from the enabled/disabled sources.
- * @return boolean True on success
- **/
-YCPValue
-PkgModuleFunctions::SourceLoadImpl(PkgProgress &progress)
+// helper function
+zypp::Url PkgModuleFunctions::shortenUrl(const zypp::Url &url)
{
- bool success = true;
+ std::string url_path = url.getPathName();
+ std::string begin_path;
+ std::string end_path;
- int repos_to_load = 0;
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
+ // try to convert 'http://server/dir1/dir2/dir3/dir4' -> 'http://server/dir1/.../dir4'
+ std::string::size_type pos_first = url_path.find("/");
+ if (pos_first == 0)
{
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
- {
- repos_to_load++;
- }
+ pos_first = url_path.find("/", 1);
}
- // set max. value (3 steps per repository - refresh, rebuild, load)
- zypp::ProgressData prog_total(repos_to_load * 3);
- prog_total.sendTo(progress.Receiver());
-
- zypp::RepoManager repomanager = CreateRepoManager();
-
- // refresh metadata
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
+ if (pos_first == std::string::npos)
{
- // load resolvables only from enabled repos which are not deleted
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
- {
- // sub tasks
- zypp::CombinedProgressData refresh_subprogress(prog_total, 1);
+ const int num = 5;
- if (AnyResolvableFrom((*it)->repoInfo().alias()))
- {
- y2milestone("Resolvables from '%s' are already present, not loading", (*it)->repoInfo().alias().c_str());
- }
- else
- {
- // autorefresh the source
- if ((*it)->repoInfo().autorefresh())
- {
- try
- {
- y2milestone("Autorefreshing source: %s", (*it)->repoInfo().alias().c_str());
- RefreshWithCallbacks((*it)->repoInfo());
-
- zypp::ProgressData prog(1);
- prog.sendTo(refresh_subprogress);
- RefreshWithCallbacks((*it)->repoInfo());
- prog.toMax();
- }
- // NOTE: subtask progresses are reported as done in the descructor
- // no need to handle them in the exception code
- catch (const zypp::Exception& excpt)
- {
- y2error ("Error in SourceLoad: %s", excpt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- success = false;
- }
- }
- }
- }
+ // "/" not found use the beginning and the end part
+ // 'http://server/very_long_directory_name' -> 'http://server/very_..._name'
+ begin_path = std::string(url_path, 0, num);
+ end_path = std::string(url_path, url_path.size() - num - 1, num);
}
-
- progress.NextStage();
-
- // rebuild cache
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
+ else
{
- // load resolvables only from enabled repos which are not deleted
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
+ unsigned int pos_last = url_path.rfind("/");
+ if (pos_last == url_path.size() - 1)
{
- // sub tasks
- zypp::CombinedProgressData rebuild_subprogress(prog_total, 1);
-
- if (AnyResolvableFrom((*it)->repoInfo().alias()))
- {
- y2milestone("Resolvables from '%s' are already present, not loading", (*it)->repoInfo().alias().c_str());
- }
- else
- {
- // autorefresh the source
- if ((*it)->repoInfo().autorefresh())
- {
- try
- {
- // rebuild cache (the default policy is "if needed")
- y2milestone("Rebuilding cache for '%s'...", (*it)->repoInfo().alias().c_str());
-
- zypp::ProgressData prog(1);
- prog.sendTo(rebuild_subprogress);
- repomanager.buildCache((*it)->repoInfo());
- prog.toMax();
- }
- // NOTE: subtask progresses are reported as done in the descructor
- // no need to handle them in the exception code
- catch (const zypp::Exception& excpt)
- {
- y2error ("Error in SourceLoad: %s", excpt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- success = false;
- }
- }
- }
+ pos_last = url_path.rfind("/", url_path.size() - 1);
}
- }
- progress.NextStage();
-
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- // load resolvables only from enabled repos which are not deleted
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
+ if (pos_last == pos_first || pos_last < pos_first)
{
- // sub tasks
- zypp::CombinedProgressData load_subprogress(prog_total, 1);
-
- if (AnyResolvableFrom((*it)->repoInfo().alias()))
- {
- y2milestone("Resolvables from '%s' are already present, not loading", (*it)->repoInfo().alias().c_str());
- }
- else
- {
- zypp::ProgressData prog(1);
- prog.sendTo(load_subprogress);
-
- // load objects
- success = LoadResolvablesFrom((*it)->repoInfo()) && success;
+ const int num = 5;
- prog.toMax();
- }
+ // "/" not found use the beginning and the end part
+ begin_path = std::string(url_path, 0, num);
+ end_path = std::string(url_path, url_path.size() - num - 1, num);
}
- }
-
- // report 100%
- prog_total.toMax();
-
- return YCPBoolean(success);
-}
-
-
-/****************************************************************************************
- * @builtin SourceStartManager
- *
- * @short Start the source manager - restore the sources and load the resolvables
- * @description
- * Calls SourceRestore(), if argument enable is true SourceLoad() is called.
- * @param boolean enable If true the resolvables are loaded from the enabled sources
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceStartManager (const YCPBoolean& enable)
-{
- PkgProgress pkgprogress(_callbackHandler);
-
- // display the progress only when 'enable' is true
- if (enable->value())
- {
- std::list<std::string> stages;
- stages.push_back("Load Sources");
- stages.push_back("Refresh Sources");
- stages.push_back("Rebuild Cache");
- stages.push_back("Load Data");
-
- // 3 steps per repository (download, cache rebuild, load resolvables)
- pkgprogress.Start("Loading the Package Manager...", stages, "help");
- }
-
- YCPValue ret = SourceStartManagerImpl(enable, pkgprogress);
-
- if (enable->value())
- {
- pkgprogress.Done();
- }
-
- return ret;
-}
-
-/****************************************************************************************
- * @builtin SourceStartManager
- *
- * @short Start the source manager - restore the sources and load the resolvables
- * @description
- * Calls SourceRestore(), if argument enable is true SourceLoad() is called.
- * @param boolean enable If true the resolvables are loaded from the enabled sources
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceStartManagerImpl(const YCPBoolean& enable, PkgProgress &progress)
-{
- YCPValue success = SourceRestore();
-
- progress.NextStage();
-
- if( enable->value() )
- {
- if (!success->asBoolean()->value())
+ else
{
- y2warning("SourceStartManager: Some sources have not been restored, loading only the active sources...");
+ begin_path = std::string(url_path, 0, pos_first + 1);
+ end_path = std::string(url_path, pos_last);
}
-
- // enable all sources and load the resolvables
- success = YCPBoolean(SourceLoadImpl(progress)->asBoolean()->value() && success->asBoolean()->value());
- }
-
- return success;
-}
-
-/****************************************************************************************
- * @builtin SourceStartCache
- *
- * @short Make sure the InstSrcManager is up, and return the list of SrcIds.
- * @description
- * Make sure the InstSrcManager is up, and return the list of SrcIds.
- * In fact nothing more than:
- *
- * <code>
- * SourceStartManager( enabled_only );
- * return SourceGetCurrent( enabled_only );
- * </code>
- *
- * @param boolean enabled_only If true, make sure all InstSrces are enabled according to
- * their default, and return the Ids of enabled InstSrces only. If false, return
- * the Ids of all known InstSrces.
- *
- * @return list<integer> list of SrcIds
- **/
-YCPValue
-PkgModuleFunctions::SourceStartCache (const YCPBoolean& enabled)
-{
- try
- {
- SourceStartManager(enabled);
-
- return SourceGetCurrent(enabled);
- }
- catch (const zypp::Exception& excpt)
- {
- y2error ("Error in SourceStartCache: %s", excpt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- }
- // catch an exception from boost (e.g. a file cannot be read by non-root user)
- catch (const std::exception& err)
- {
- y2error ("Error in SourceStartCache: %s", err.what());
- _last_error.setLastError(err.what());
- }
- catch (...)
- {
- y2error("Unknown error in SourceStartCache");
}
- return YCPList();
-}
-
-/****************************************************************************************
- * @builtin SourceCleanupBroken
- *
- * @short Clean up all sources that were not properly restored on the last
- * call of SourceStartManager or SourceStartCache.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceCleanupBroken ()
-{
- y2warning("Pkg::SourceCleanupBroken() is obsoleted, it's not needed anymore.");
- return YCPBoolean(true);
-}
+ std::string new_path = begin_path + "..." + end_path;
+ zypp::Url ret(url);
-/****************************************************************************************
- * @builtin SourceGetCurrent
- *
- * @short Return the list of all InstSrc Ids.
- *
- * @param boolean enabled_only If true, or omitted, return the Ids of all enabled InstSrces.
- * If false, return the Ids of all known InstSrces.
- *
- * @return list<integer> list of SrcIds (integer)
- **/
-YCPValue
-PkgModuleFunctions::SourceGetCurrent (const YCPBoolean& enabled)
-{
- YCPList res;
-
- std::vector<YRepo_Ptr>::size_type index = 0;
- for( std::vector<YRepo_Ptr>::const_iterator it = repos.begin(); it != repos.end() ; ++it, ++index )
- {
- // ignore disabled sources if requested
- if (enabled->value())
- {
- // Note: enabled() is tribool!
- if ((*it)->repoInfo().enabled())
- {
- }
- else if (!(*it)->repoInfo().enabled())
- {
- continue;
- }
- else
- {
- continue;
- }
- }
-
- // ignore deleted sources
- if ((*it)->isDeleted())
- {
- continue;
- }
-
- res->add( YCPInteger(index) );
- }
-
- return res;
-}
-
-/****************************************************************************************
- * @builtin SourceReleaseAll
- *
- * @short Release all medias hold by all sources
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceReleaseAll ()
-{
- y2milestone("Releasing all sources...");
- bool ret = true;
-
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- try
- {
- (*it)->mediaAccess()->release();
- }
- catch (const zypp::media::MediaException & ex)
- {
- y2warning("Failed to release media for repo: %s", ex.msg().c_str());
- ret = false;
- }
- }
-
- return YCPBoolean(ret);
-}
-
-/******************************************************************************
- * @builtin SourceSaveAll
- *
- * @short Save all InstSrces.
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceSaveAll ()
-{
- y2milestone("Saving the source setup...");
-
- zypp::RepoManager repomanager = CreateRepoManager();
-
- // remove deleted repos (the old configurations) at first
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- // the repo has been removed
- if ((*it)->isDeleted())
- {
- std::string repo_alias = (*it)->repoInfo().alias();
-
- try
- {
- // remove the metadata
- zypp::RepoStatus raw_metadata_status = repomanager.metadataStatus((*it)->repoInfo());
- if (!raw_metadata_status.empty())
- {
- y2milestone("Removing metadata for source '%s'...", repo_alias.c_str());
- repomanager.cleanMetadata((*it)->repoInfo());
- }
-
- // remove the cache
- if (repomanager.isCached((*it)->repoInfo()))
- {
- y2milestone("Removing cache for '%s'...", repo_alias.c_str());
- repomanager.cleanCache((*it)->repoInfo());
- }
-
- repomanager.getRepositoryInfo(repo_alias);
- y2milestone("Removing repository '%s'", repo_alias.c_str());
- repomanager.removeRepository((*it)->repoInfo());
- }
- catch (const zypp::repo::RepoNotFoundException &ex)
- {
- // repository not found -- not critical, continue
- y2warning("No such repository: %s", repo_alias.c_str());
- }
- catch (const zypp::Exception & excpt)
- {
- y2error("Pkg::SourceSaveAll has failed: %s", excpt.msg().c_str() );
- _last_error.setLastError(ExceptionAsString(excpt));
- return YCPBoolean(false);
- }
- }
- }
-
- // save all repos (the current configuration)
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- if (!(*it)->isDeleted())
- {
- std::string current_alias = (*it)->repoInfo().alias();
-
- try
- {
- try
- {
- // if the repository already exists then just modify it
- repomanager.getRepositoryInfo(current_alias);
- y2milestone("Modifying repository '%s'", current_alias.c_str());
- repomanager.modifyRepository(current_alias, (*it)->repoInfo());
- }
- catch (const zypp::repo::RepoNotFoundException &ex)
- {
- // the repository was not found, add it
- y2milestone("Adding repository '%s'", current_alias.c_str());
- repomanager.addRepository((*it)->repoInfo());
- }
- }
- catch (zypp::Exception & excpt)
- {
- y2error("Pkg::SourceSaveAll has failed: %s", excpt.msg().c_str() );
- _last_error.setLastError(ExceptionAsString(excpt));
- return YCPBoolean(false);
- }
- }
- }
-
- y2milestone("All sources have been saved");
-
- return YCPBoolean(true);
-}
-
-/****************************************************************************************
- * @builtin SourceFinishAll
- *
- * @short Save and then disable all InstSrces.
- * @description
- * If there are no enabled sources, do nothing
- * (idempotence hack, broken design: #155459, #176013, use SourceSaveAll).
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceFinishAll ()
-{
- try
- {
- bool found_enabled = false;
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
- {
- found_enabled = true;
- break;
- }
- }
-
- if (!found_enabled)
- {
- y2milestone( "No enabled sources, skipping SourceFinishAll()" );
- return YCPBoolean( true );
- }
-
- SourceSaveAll();
-
- y2milestone( "Disabling all sources...") ;
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- (*it)->repoInfo().setEnabled(false);
- }
- // TODO FIXME remove all resolvables??
- }
- catch (zypp::Exception & excpt)
- {
- y2error("Pkg::SourceFinishAll has failed: %s", excpt.msg().c_str() );
- _last_error.setLastError(ExceptionAsString(excpt));
- return YCPBoolean(false);
- }
-
- y2milestone("All sources have been saved and disabled");
-
- return YCPBoolean(true);
-}
-
-/////////////////////////////////////////////////////////////////////////////////////////
-// Query individual sources
-/////////////////////////////////////////////////////////////////////////////////////////
-
-/****************************************************************************************
- * @builtin SourceGeneralData
- *
- * @short Get general data about the source
- * @description
- * Return general data about the source as a map:
- *
- * <code>
- * $[
- * "enabled" : YCPBoolean,
- * "autorefresh": YCPBoolean,
- * "product_dir": YCPString,
- * "type" : YCPString,
- * "url" : YCPString (without password, but see SourceURL),
- * "alias" : YCPString,
- * "name" : YCPString,
- * ];
- *
- * </code>
- * @param integer SrcId Specifies the InstSrc to query.
- * @return map
- **/
-YCPValue
-PkgModuleFunctions::SourceGeneralData (const YCPInteger& id)
-{
- YCPMap data;
-
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPVoid ();
-
- // convert type to the old strings ("YaST", "YUM" or "Plaindir")
- std::string srctype = zypp2yastType(repo->repoInfo().type().asString());
-
- data->add( YCPString("enabled"), YCPBoolean(repo->repoInfo().enabled()));
- data->add( YCPString("autorefresh"), YCPBoolean(repo->repoInfo().autorefresh()));
- data->add( YCPString("type"), YCPString(srctype));
- data->add( YCPString("product_dir"), YCPString(repo->repoInfo().path().asString()));
-
- // check if there is an URL
- if (repo->repoInfo().baseUrlsBegin() != repo->repoInfo().baseUrlsEnd())
- {
- data->add( YCPString("url"), YCPString(repo->repoInfo().baseUrlsBegin()->asString()));
- }
-
- data->add( YCPString("alias"), YCPString(repo->repoInfo().alias()));
- data->add( YCPString("name"), YCPString(repo->repoInfo().name()));
-
- YCPList base_urls;
- for( zypp::RepoInfo::urls_const_iterator it = repo->repoInfo().baseUrlsBegin(); it != repo->repoInfo().baseUrlsEnd(); ++it)
- {
- base_urls->add(YCPString(it->asString()));
- }
- data->add( YCPString("base_urls"), base_urls);
-
- data->add( YCPString("mirror_list"), YCPString(repo->repoInfo().mirrorListUrl().asString()));
-
- return data;
-}
-
-/******************************************************************************
- * @builtin SourceURL
- *
- * @short Get full source URL, including password
- * @param integer SrcId Specifies the InstSrc to query.
- * @return string or nil on failure
- **/
-YCPValue
-PkgModuleFunctions::SourceURL (const YCPInteger& id)
-{
-
- const YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPVoid();
-
- std::string url;
-
- if (repo->repoInfo().baseUrlsBegin() != repo->repoInfo().baseUrlsEnd())
- {
- // #186842
- url = repo->repoInfo().baseUrlsBegin()->asCompleteString();
- }
-
- return YCPString(url);
-}
-
-/****************************************************************************************
- * @builtin SourceMediaData
- * @short Return media data about the source
- * @description
- * Return media data about the source as a map:
- *
- * <code>
- * $["media_count": YCPInteger,
- * "media_id" : YCPString,
- * "media_vendor" : YCPString,
- * "url" : YCPString,
- * ];
- * </code>
- *
- * @param integer SrcId Specifies the InstSrc to query.
- * @return map
- **/
-YCPValue
-PkgModuleFunctions::SourceMediaData (const YCPInteger& id)
-{
- YCPMap data;
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPVoid ();
-
- std::string alias = repo->repoInfo().alias();
- bool found_resolvable = false;
- int max_medium = 1;
-
- for (zypp::ResPool::const_iterator it = zypp_ptr()->pool().begin()
- ; it != zypp_ptr()->pool().end()
- ; ++it)
- {
- if (it->resolvable()->repository().info().alias() == alias)
- {
- int medium = it->resolvable()->mediaNr();
-
- if (medium > max_medium)
- {
- max_medium = medium;
- }
- }
- }
-
- if (found_resolvable)
- {
- data->add( YCPString("media_count"), YCPInteger(max_medium));
- }
- else
- {
- y2error("No resolvable from repository '%s' found, cannot get number of media (use Pkg::SourceLoad() to load the resolvables)", alias.c_str());
- }
-
- y2warning("Pkg::SourceMediaData() doesn't return \"media_id\" and \"media_vendor\" values anymore.");
-
- // SourceMediaData returns URLs without password
- if (repo->repoInfo().baseUrlsBegin() != repo->repoInfo().baseUrlsEnd())
- {
- data->add( YCPString("url"), YCPString(repo->repoInfo().baseUrlsBegin()->asString()));
-
- // add all base URLs
- YCPList base_urls;
- for( zypp::RepoInfo::urls_const_iterator it = repo->repoInfo().baseUrlsBegin(); it != repo->repoInfo().baseUrlsEnd(); ++it)
- {
- base_urls->add(YCPString(it->asString()));
- }
- data->add( YCPString("base_urls"), base_urls);
- }
-
- return data;
-}
-
-/****************************************************************************************
- * @builtin SourceProductData
- * @short Return Product data about the source
- * @param integer SrcId Specifies the InstSrc to query.
- * @description
- * Product data about the source as a map:
- *
- * <code>
- * $[
- * "label" : YCPString,
- * "vendor" : YCPString,
- * "productname" : YCPString,
- * "productversion" : YCPString,
- * "relnotesurl" : YCPString,
- * ];
- * </code>
- *
- * @return map
- **/
-YCPValue
-PkgModuleFunctions::SourceProductData (const YCPInteger& src_id)
-{
- YCPMap ret;
-
- try
- {
- // find a product for the given source
- zypp::ResPool::byKind_iterator it = zypp_ptr()->pool().byKindBegin(zypp::ResTraits<zypp::Product>::kind);
-
- for( ; it != zypp_ptr()->pool().byKindEnd(zypp::ResTraits<zypp::Product>::kind) ; ++it)
- {
- zypp::Product::constPtr product = boost::dynamic_pointer_cast<const zypp::Product>( it->resolvable() );
-
- if( logFindAlias(product->repository().info().alias()) == src_id->value() )
- {
- ret->add( YCPString("label"), YCPString( product->summary() ) );
- ret->add( YCPString("vendor"), YCPString( product->vendor() ) );
- ret->add( YCPString("productname"), YCPString( product->name() ) );
- ret->add( YCPString("productversion"), YCPString( product->edition().version() ) );
- ret->add( YCPString("relnotesurl"), YCPString( product->releaseNotesUrl().asString()));
-
- #warning SourceProductData not finished
- /*
- data->add( YCPString("datadir"), YCPString( descr->content_datadir().asString() ) );
- TODO (?): "baseproductname", "baseproductversion", "defaultbase", "architectures",
- "requires", "linguas", "labelmap", "language", "timezone", "descrdir", "datadir"
- */
-
- break;
- }
- }
-
- if( it == zypp_ptr()->pool().byKindEnd(zypp::ResTraits<zypp::Product>::kind) )
- {
- y2error ("Product for source '%lld' not found", src_id->value());
- }
- }
- catch (...)
- {
- }
-
- return ret;
-}
-
-/****************************************************************************************
- * @builtin SourceProduct
- * @short Obsoleted function, do not use, see SourceProductData builtin
- * @deprecated
- * @param integer
- * @return map empty map
- **/
-YCPValue
-PkgModuleFunctions::SourceProduct (const YCPInteger& id)
-{
- /* TODO FIXME */
- y2error("Pkg::SourceProduct() is obsoleted, use Pkg::SourceProductData() instead!");
- return YCPMap();
-}
-
-
-YCPValue PkgModuleFunctions::SourceProvideFileCommon(const YCPInteger &id,
- const YCPInteger &mid,
- const YCPString& f,
- const YCPBoolean & optional)
-{
- CallInitDownload(std::string(_("Downloading ") + f->value()));
-
- bool found = true;
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- found = false;
-
- extern ZyppRecipients::MediaChangeSensitivity _silent_probing;
- // remember the current value
- ZyppRecipients::MediaChangeSensitivity _silent_probing_old = _silent_probing;
-
- // disable media change callback for optional file
- if (optional->value())
- _silent_probing = ZyppRecipients::MEDIA_CHANGE_OPTIONALFILE;
-
- zypp::filesystem::Pathname path; // FIXME use ManagedMedia
- if (found)
- {
- try
- {
- path = repo->mediaAccess()->provideFile(f->value(), mid->value());
- y2milestone("local path: '%s'", path.asString().c_str());
- }
- catch (const zypp::Exception& excpt)
- {
- found = false;
-
- if (!optional->value())
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2milestone("File not found: %s", f->value_cstr());
- }
- }
- }
-
- // set the original probing value
- _silent_probing = _silent_probing_old;
-
- CallDestDownload();
-
- if (found)
- {
- return YCPString(path.asString());
- }
- else
- {
- return YCPVoid();
- }
-}
-
-
-/****************************************************************************************
- * @builtin SourceProvideFile
- *
- * @short Make a file available at the local filesystem
- * @description
- * Let an InstSrc provide some file (make it available at the local filesystem).
- *
- * @param integer SrcId Specifies the InstSrc .
- * @param integer medianr Number of the media the file is located on ('1' for the 1st media).
- * @param string file Filename relative to the media root.
- *
- * @return string local path as string
- **/
-YCPValue
-PkgModuleFunctions::SourceProvideFile (const YCPInteger& id, const YCPInteger& mid, const YCPString& f)
-{
- return SourceProvideFileCommon(id, mid, f, false /*optional*/);
-}
-
-/****************************************************************************************
- * @builtin SourceProvideOptionalFile
- *
- * @short Make an optional file available at the local filesystem
- * @description
- * Let an InstSrc provide some file (make it available at the local filesystem).
- * If the file doesn't exist don't ask user for another medium and return nil
- *
- * @param integer SrcId Specifies the InstSrc .
- * @param integer medianr Number of the media the file is located on ('1' for the 1st media).
- * @param string file Filename relative to the media root.
- *
- * @return string local path as string
- **/
-YCPValue
-PkgModuleFunctions::SourceProvideOptionalFile (const YCPInteger& id, const YCPInteger& mid, const YCPString& f)
-{
- return SourceProvideFileCommon(id, mid, f, true /*optional*/);
-}
-
-/****************************************************************************************
- * @builtin SourceProvideDir
- * @short make a directory available at the local filesystem
- * @description
- * Let an InstSrc provide some directory (make it available at the local filesystem) and
- * all the files within it (non recursive).
- *
- * @param integer SrcId Specifies the InstSrc .
- * @param integer medianr Number of the media the file is located on ('1' for the 1st media).
- * @param string dir Directoryname relative to the media root.
- * @return string local path as string
- */
-YCPValue
-PkgModuleFunctions::SourceProvideDir (const YCPInteger& id, const YCPInteger& mid, const YCPString& d)
-{
- y2warning("Pkg::SourceProvideDir() is obsoleted use Pkg::SourceProvideDirectory() instead");
- // non optional, non recursive
- return SourceProvideDirectory(id, mid, d, false, false);
-}
-
-
-/****************************************************************************************
- * @builtin SourceProvideDirectory
- * @short make a directory available at the local filesystem
- * @description
- * Download a directory from repository (make it available at the local filesystem) and
- * all the files within it.
- *
- * @param integer id repository to use (id)
- * @param integer mid Number of the media where the directory is located on ('1' for the 1st media).
- * @param string d Directory name relative to the media root.
- * @param boolean optional set to true if the directory may not exist (do not report errors)
- * @param boolean recursive set to true to provide all subdirectories recursively
- * @return string local path as string or nil when an error occured
- */
-YCPValue
-PkgModuleFunctions::SourceProvideDirectory(const YCPInteger& id, const YCPInteger& mid, const YCPString& d, const YCPBoolean &optional, const YCPBoolean &recursive)
-{
- CallInitDownload(std::string(_("Downloading ") + d->value()));
-
- bool found = true;
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- found = false;
-
- zypp::filesystem::Pathname path; // FIXME user ManagedMedia
-
- extern ZyppRecipients::MediaChangeSensitivity _silent_probing;
- // remember the current value
- ZyppRecipients::MediaChangeSensitivity _silent_probing_old = _silent_probing;
-
- // disable media change callback for optional file
- if (optional->value())
- _silent_probing = ZyppRecipients::MEDIA_CHANGE_OPTIONALFILE;
-
- if (found)
- {
- try
- {
- path = repo->mediaAccess()->provideDir(d->value(), recursive->value(), mid->value());
- }
- catch (const zypp::Exception& excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2milestone ("Directory not found: %s", d->value_cstr());
- found = false;
- }
- }
-
- // set the original probing value
- _silent_probing = _silent_probing_old;
-
- CallDestDownload();
-
- if (found)
- {
- return YCPString(path.asString());
- }
- else
- {
- return YCPVoid();
- }
-}
-
-/****************************************************************************************
- * @builtin SourceChangeUrl
- * @short Change Source URL
- * @description
- * Change url of an InstSrc. Used primarely when re-starting during installation
- * and a cd-device changed from hdX to srX since ide-scsi was activated.
- * @param integer SrcId Specifies the InstSrc.
- * @param string url The new url to use.
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceChangeUrl (const YCPInteger& id, const YCPString& u)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- try
- {
- if (repo->repoInfo().baseUrlsSize() > 1)
- {
- // store current urls
- std::set<zypp::Url> baseUrls (repo->repoInfo().baseUrlsBegin(), repo->repoInfo().baseUrlsEnd());
-
- // reset url list and store the new one there
- repo->repoInfo().setBaseUrl(zypp::Url(u->value()));
-
- // add the rest of base urls
- for (std::set<zypp::Url>::const_iterator i = baseUrls.begin();
- i != baseUrls.end(); ++i)
- repo->repoInfo().addBaseUrl(*i);
- }
- else
- repo->repoInfo().setBaseUrl(zypp::Url(u->value()));
- }
- catch (const zypp::Exception & excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error ("Cannot set the new URL for source %s (%lld): %s",
- repo->repoInfo().alias().c_str(), id->asInteger()->value(), excpt.msg().c_str());
- return YCPBoolean(false);
- }
-
- return YCPBoolean(true);
-}
-
-/****************************************************************************************
- * @builtin SourceInstallOrder
- *
- * @short not implemented, do not use (Explicitly set an install order.)
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceInstallOrder (const YCPMap& ord)
-{
- /* TODO FIXME
- YCPList args;
- args->add (ord);
-
- //-------------------------------------------------------------------------------------//
- YcpArgLoad decl(__FUNCTION__);
-
- YCPMap & order_map( decl.arg<YT_MAP, YCPMap>() );
-
- if ( ! decl.load( args ) ) {
- return pkgError_bad_args;
- }
- //-------------------------------------------------------------------------------------//
-
- InstSrcManager::InstOrder order;
- order.reserve( order_map->size() );
- bool error = false;
-
- for ( YCPMapIterator it = order_map->begin(); it != order_map->end(); ++it ) {
-
- if ( it.value()->isInteger() ) {
- InstSrc::UniqueID uId( it.value()->asInteger()->value() );
- InstSrcManager::ISrcId source_id( _y2pm.instSrcManager().getSourceByID( uId ) );
- if ( source_id ) {
- if ( source_id->enabled() ) {
- order.push_back( uId ); // finaly ;)
-
- } else {
- y2error ("order map entry '%s:%s': source not enabled",
- it.key()->toString().c_str(),
- it.value()->toString().c_str() );
- error = true;
- }
- } else {
- y2error ("order map entry '%s:%s': bad source id",
- it.key()->toString().c_str(),
- it.value()->toString().c_str() );
- error = true;
- }
- } else {
- y2error ("order map entry '%s:%s': integer value expected",
- it.key()->toString().c_str(),
- it.value()->toString().c_str() );
- error = true;
- }
- }
- if ( error ) {
- return pkgError( Error::E_bad_args );
- }
-
- // store new instorder
- _y2pm.instSrcManager().setInstOrder( order );
-*/
-
-#warning SourceInstallOrder is not implemented
- return YCPBoolean( true );
-}
-
-
-static std::string timestamp ()
-{
- time_t t = time(NULL);
- struct tm * tmp = localtime(&t);
-
- if (tmp == NULL) {
- return "";
- }
-
- char outstr[50];
- if (strftime(outstr, sizeof(outstr), "%Y%m%d-%H%M%S", tmp) == 0) {
- return "";
- }
- return outstr;
-}
-
-/**
- * Take the ?alias=foo part of old_url, if any, and return it,
- * putting the rest to new_url.
- * \throws Exception on malformed URLs I guess
- */
-static std::string removeAlias (const zypp::Url & old_url,
- zypp::Url & new_url)
-{
- std::string alias;
- new_url = old_url;
- zypp::url::ParamMap query = new_url.getQueryStringMap ();
- zypp::url::ParamMap::iterator alias_it = query.find ("alias");
- if (alias_it != query.end ())
- {
- alias = alias_it->second;
- query.erase (alias_it);
- new_url.setQueryStringMap (query);
- }
- return alias;
-}
-
-std::string PkgModuleFunctions::UniqueAlias(const std::string &alias)
-{
- // make a copy
- std::string ret = alias;
-
- unsigned int id = 0;
- while(aliasExists(ret))
- {
- y2milestone("Alias %s already found: %lld", ret.c_str(), logFindAlias(ret));
-
- // the alias already exists - add a counter
- std::ostringstream ostr;
- ostr << alias << "_" << id;
-
- ret = ostr.str();
-
- y2milestone("Using alias %s", ret.c_str());
- ++id;
- }
-
- return ret;
-}
-
-
-/**
- * helper - add "mountoptions=ro" for mountable URL schemes if "mountoptions" option is not empty and
- * "rw" or "ro" option is missing
- */
-zypp::Url addRO(const zypp::Url &url)
-{
- zypp::Url ret(url);
- std::string scheme = zypp::str::toLower(url.getScheme());
-
- if (scheme == "nfs"
- || scheme == "hd"
- || scheme == "smb"
- || scheme == "iso"
- || scheme == "cd"
- || scheme == "dvd"
- )
- {
- const std::string mountoptions = "mountoptions";
- zypp::media::Mount::Options options(url.getQueryParam(mountoptions));
-
- y2debug("Current mountoptions: %s", options.asString().c_str());
-
- // if mountoptions are empty lizypp uses "ro" by default
- // don't override "rw" option from application
- // don't add "ro" if it's already present
- if (!options.empty() && !options.has("rw") && !options.has("ro"))
- {
- options["ro"];
-
- ret.setQueryParam(mountoptions, options.asString());
- y2milestone("Adding read only mount option: '%s' -> '%s'", url.asString().c_str(), ret.asString().c_str());
- }
- }
-
- return ret;
-}
-
-// helper function
-zypp::Url PkgModuleFunctions::shortenUrl(const zypp::Url &url)
-{
- std::string url_path = url.getPathName();
- std::string begin_path;
- std::string end_path;
-
- // try to convert 'http://server/dir1/dir2/dir3/dir4' -> 'http://server/dir1/.../dir4'
- std::string::size_type pos_first = url_path.find("/");
- if (pos_first == 0)
- {
- pos_first = url_path.find("/", 1);
- }
-
- if (pos_first == std::string::npos)
- {
- const int num = 5;
-
- // "/" not found use the beginning and the end part
- // 'http://server/very_long_directory_name' -> 'http://server/very_..._name'
- begin_path = std::string(url_path, 0, num);
- end_path = std::string(url_path, url_path.size() - num - 1, num);
- }
- else
- {
- unsigned int pos_last = url_path.rfind("/");
- if (pos_last == url_path.size() - 1)
- {
- pos_last = url_path.rfind("/", url_path.size() - 1);
- }
-
- if (pos_last == pos_first || pos_last < pos_first)
- {
- const int num = 5;
-
- // "/" not found use the beginning and the end part
- begin_path = std::string(url_path, 0, num);
- end_path = std::string(url_path, url_path.size() - num - 1, num);
- }
- else
- {
- begin_path = std::string(url_path, 0, pos_first + 1);
- end_path = std::string(url_path, pos_last);
- }
- }
-
- std::string new_path = begin_path + "..." + end_path;
- zypp::Url ret(url);
-
- // use the shorter path
- ret.setPathName(new_path);
- // remove query parameters
- ret.setQueryString("");
- // remove fragmet
- ret.setFragment("");
-
- y2milestone("Using shortened URL: '%s' -> '%s'", url.asString().c_str(), ret.asString().c_str());
- return ret;
-}
-
-/** Create a Source and immediately put it into the SourceManager.
- * \return the SourceId
- * \throws Exception if Source creation fails
-*/
-std::vector<zypp::RepoInfo>::size_type
-PkgModuleFunctions::createManagedSource( const zypp::Url & url_r,
- const zypp::Pathname & path_r,
- const bool base_source,
- const std::string& type,
- const std::string &alias_r )
-{
- // parse URL
- y2milestone ("Original URL: %s, product directory: %s", url_r.asString().c_str(), path_r.asString().c_str());
-
- // #158850#c17, if the URL contains an alias, we use that
- zypp::Url url;
-
- std::string alias = removeAlias(url_r, url);
- y2milestone("Alias from URL: '%s'", alias.c_str());
-
-#warning FIXME: use base_source (base_source vs. addon) (will be probably not needed)
-
- // repository type
- zypp::repo::RepoType repotype;
- zypp::RepoManager repomanager = CreateRepoManager();
-
- if (!type.empty())
- {
- try
- {
- // do conversion from the Yast type ("YaST", "YUM", "Plaindir")
- // to libzypp type ("yast", "yum", "plaindir")
- repotype = repotype.parse(yast2zyppType(type));
- }
- catch (zypp::repo::RepoUnknownTypeException &e)
- {
- y2warning("Unknown source type '%s'", type.c_str());
- }
- }
-
- // the type is not specified or is wrong, autoprobe the type
- if (repotype == zypp::repo::RepoType::NONE)
- {
- zypp::Url probe_url(url_r);
-
- if (!path_r.asString().empty())
- {
- zypp::Pathname pth(probe_url.getPathName());
- pth /= path_r;
-
- probe_url.setPathName(pth.asString());
- }
-
- y2milestone("Probing source type: '%s'", probe_url.asString().c_str());
-
- // autoprobe type of the repository
- repotype = ProbeWithCallbacks(probe_url);
- }
-
- y2milestone("Using source type: %s", repotype.asString().c_str());
-
-
- // create source definition object
- zypp::RepoInfo repo;
-
- std::string name;
-
- // set alias and name
- if (alias.empty())
- {
- // alias not set via URL, use the passed alias or the URL path
- if (alias_r.empty())
- {
- // use the last path element in URL
- std::string url_path = url.getPathName();
-
- std::string::size_type pos_begin = url_path.rfind("/");
- std::string::size_type pos_end = std::string::npos;
-
- // ignore the trailing slash
- if (pos_begin == url_path.size() - 1)
- {
- pos_begin = url_path.rfind("/", url_path.size() - 2);
-
- if (pos_begin != std::string::npos)
- {
- pos_end = url_path.size() - pos_begin - 2;
- }
- }
- else
- {
- pos_end = url_path.size() - pos_begin - 1;
- }
-
- // ignore the found slash character
- pos_begin++;
-
- alias = std::string(url_path, pos_begin, pos_end);
-
- y2milestone("Alias from URL path: %s", alias.c_str());
-
- // fallback
- if (alias.empty())
- {
- y2milestone("URL alias is empty using 'Repository'");
- alias = "Repository";
- }
- }
- else
- {
- alias = alias_r;
- }
-
- name = alias;
- }
- else
- {
- name = alias;
- }
-
-
- y2milestone("Name of the repository: '%s'", name.c_str());
-
- // alias must be unique, add a suffix if it's already used
- alias = UniqueAlias(alias);
-
- // add read only mount option to the URL if needed
- url = addRO(url);
-
- bool autorefresh = true;
-
- std::string scheme = zypp::str::toLower(url.getScheme());
- if (scheme == "cd" || scheme == "dvd")
- {
- y2milestone("Disabling autorefresh for CD/DVD repository");
- autorefresh = false;
- }
-
- repo.setAlias(alias);
- repo.setName(name);
- repo.setType(repotype);
- repo.addBaseUrl(url);
- repo.setPath(path_r);
- repo.setEnabled(true);
- repo.setAutorefresh(autorefresh);
-
- // set metadata path (#293428)
- zypp::Pathname metadatapath = repomanager.metadataPath(repo);
- repo.setMetadataPath(metadatapath);
-
- y2milestone("Adding source '%s' (%s, dir: %s)", repo.alias().c_str(), url.asString().c_str(), path_r.asString().c_str());
- // note: exceptions should be caught by the calling code
- RefreshWithCallbacks(repo);
-
- // build cache if needed
- if (!repomanager.isCached(repo))
- {
- y2milestone("Caching source '%s'...", repo.alias().c_str());
- repomanager.buildCache(repo);
- }
-
- repos.push_back(new YRepo(repo));
-
- y2milestone("Added source '%s': '%s', enabled: %s, autorefresh: %s",
- repo.alias().c_str(),
- repo.baseUrlsBegin()->asString().c_str(),
- repo.enabled() ? "true" : "false",
- repo.autorefresh() ? "true" : "false"
- );
-
- // the source is at the end of the list
- return repos.size() - 1;
-}
-
-/****************************************************************************************
- * @builtin RepositoryAdd
- *
- * @short Register a new repository
- * @description
- * Adds a new repository to the internal structures. The repository is only registered,
- * metadata is not downloaded, use Pkg::SourceRefreshNow() for that. The metadata is also loaded
- * automatically when loading the repository content (Pkg::SourceLoad())
- *
- * @param map map with repository parameters: $[ "enabled" : boolean, "autorefresh" : boolean, "name" : string,
- * "alias" : string, "base_urls" : list<string>, "prod_dir" : string, "type" : string ]
- * @return integer Repository ID or nil on error
- **/
-YCPValue PkgModuleFunctions::RepositoryAdd(const YCPMap ¶ms)
-{
- zypp::RepoInfo repo;
-
- // turn on the repo by default
- repo.setEnabled(true);
- // enable autorefresh by default
- repo.setAutorefresh(true);
-
- if (!params->value( YCPString("enabled") ).isNull() && params->value(YCPString("enabled"))->isBoolean())
- {
- repo.setEnabled(params->value(YCPString("enabled"))->asBoolean()->value());
- }
-
- if (!params->value( YCPString("autorefresh") ).isNull() && params->value(YCPString("autorefresh"))->isBoolean())
- {
- repo.setAutorefresh(params->value(YCPString("autorefresh"))->asBoolean()->value());
- }
-
- std::string alias;
-
- if (!params->value( YCPString("alias") ).isNull() && params->value(YCPString("alias"))->isString())
- {
- alias = params->value(YCPString("alias"))->asString()->value();
- }
-
- if (alias.empty())
- {
- alias = timestamp();
-
- // the alias must be unique
- alias = UniqueAlias(alias);
- }
- else
- {
- if (aliasExists(alias))
- {
- ycperror("alias %s already exists", alias.c_str());
- return YCPVoid();
- }
- }
-
- repo.setAlias(alias);
-
- // use the first base URL as a fallback name
- std::string first_url;
-
- if (!params->value( YCPString("base_urls") ).isNull() && params->value(YCPString("base_urls"))->isList())
- {
- YCPList lst(params->value(YCPString("base_urls"))->asList());
-
- for (int index = 0; index < lst->size(); ++index)
- {
- if( ! lst->value(index)->isString() )
- {
- ycperror( "Pkg::RepositoryAdd(): entry not a string at index %d: %s", index, lst->toString().c_str());
- return YCPVoid();
- }
-
- zypp::Url url;
-
- try
- {
- url = lst->value(index)->asString()->value();
- zypp::Url url_new;
-
- std::string name = removeAlias(url, url_new);
-
- if (!name.empty())
- {
- repo.setName(name);
- url = url_new;
- }
-
- // add read only mount option to the URL if needed
- url = addRO(url);
- }
- catch(const zypp::Exception & expt)
- {
- y2error("Invalid URL: %s", expt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(expt));
- return YCPVoid();
- }
-
- if (index == 0)
- {
- first_url = url.asString();
- }
-
- repo.addBaseUrl(url);
- }
- }
- else
- {
- ycperror("Missing \"base_urls\" key in the map");
- return YCPVoid();
- }
-
- // check name parameter
- if (!params->value( YCPString("name") ).isNull() && params->value(YCPString("name"))->isString())
- {
- repo.setName(params->value(YCPString("name"))->asString()->value());
- }
- else
- {
- // if the key "name" is missing and the name hasn't been set by ?alias= in the URL
- // then use the first URL as the name
- if (repo.name().empty())
- {
- repo.setName(first_url);
- }
- }
-
- if (!params->value( YCPString("type") ).isNull() && params->value(YCPString("type"))->isString())
- {
- std::string type = yast2zyppType(params->value(YCPString("type"))->asString()->value());
-
- try
- {
- zypp::repo::RepoType repotype(type);
- repo.setType(repotype);
- }
- catch (zypp::repo::RepoUnknownTypeException &e)
- {
- ycperror("Unknown source type '%s': %s", type.c_str(), e.asString().c_str());
- _last_error.setLastError(ExceptionAsString(e));
- return YCPVoid();
- }
-
- }
-
- if (!params->value( YCPString("prod_dir") ).isNull() && params->value(YCPString("prod_dir"))->isString())
- {
- repo.setPath(params->value(YCPString("prod_dir"))->asString()->value());
- }
-
- // set metadata path (#293428)
- zypp::RepoManager repomanager = CreateRepoManager();
- zypp::Pathname metadatapath = repomanager.metadataPath(repo);
- repo.setMetadataPath(metadatapath);
-
- repos.push_back(new YRepo(repo));
-
- // the new source is at the end of the list
- return YCPInteger(repos.size() - 1);
-}
-
-/****************************************************************************************
- * @builtin SourceCacheCopyTo
- *
- * @short Copy cache data of all installation sources to the target
- * @description
- * Copy cache data of all installation sources to the target located below 'dir'.
- * To be called at end of initial installation.
- *
- * @param string dir Root directory of target.
- * @return boolean true on success
- **/
-YCPValue
-PkgModuleFunctions::SourceCacheCopyTo (const YCPString& dir)
-{
- // error message (followed by detailed description)
- const std::string msg = _("Error: Cannot copy the cache to the target directory\n");
-
- std::string d = dir->value();
- y2milestone("Copying source cache to '%s'...", d.c_str());
-
- if (d.empty())
- {
- y2error("Empty parameter in Pkg::SourceCacheCopyTo()!");
- return YCPBoolean(false);
- }
-
- std::string target = d + "/var/cache";
-
- // create the target dir
- const char* argv[] =
- {
- "mkdir",
- // create parent dir
- "-p",
- // finish parameter list
- "--",
- // target
- target.c_str(),
- NULL
- };
-
- // discard stderr, no pty, stderr_fd = -1, use the default locale
- zypp::ExternalProgram prog(argv, zypp::ExternalProgram::Discard_Stderr, false, -1, true);
-
- int code = prog.close();
-
- if (code)
- {
- // error message (followed by directory name)
- _last_error.setLastError(msg + _("Cannot create directory ") + target);
- y2error("Cannot create target directory %s", target.c_str());
- return YCPBoolean(false);
- }
-
- // copy /var/cache/zypp to the target system
- const char* argv2[] =
- {
- "cp",
- // preserve time stamps
- "-a",
- // recursive
- "-r",
- // finish parameter list
- "--",
- // source
- "/var/cache/zypp",
- // target
- target.c_str(),
- NULL
- };
-
- // discard stderr, no pty, stderr_fd = -1, use the default locale
- zypp::ExternalProgram prog2(argv2, zypp::ExternalProgram::Discard_Stderr, false, -1, true);
-
- int code2 = prog2.close();
-
- if (code2)
- {
- // error message
- _last_error.setLastError(msg + _("Copying failed"));
- y2error("Cannot copy /var/cache/zypp to %s", d.c_str());
- }
-
- return YCPBoolean(!code2);
-}
-
-/****************************************************************************************
- * @builtin SourceScan
- * @short Scan a Source Media
- * @description
- * Load all InstSrces found at media_url, i.e. all sources mentioned in /media.1/products.
- * If no /media.1/products is available, InstSrc is expected to be located directly
- * below media_url (product_dir: /).
- *
- * If a product_dir is provided, only the InstSrc located at media_url/product_dir is loaded.
- *
- * In contrary to @ref SourceCreate, InstSrces are loaded into the InstSrcManager,
- * but not enabled (packages and selections are not provided to the PackageManager),
- * and the SrcIds of <b>all</b> InstSrces found are returned.
- *
- * @param string url The media to scan.
- * @optarg string product_dir Restrict scan to a certain InstSrc located in media_url/product_dir.
- *
- * @return list<integer> list of SrcIds (integer).
- **/
-YCPValue
-PkgModuleFunctions::SourceScan (const YCPString& media, const YCPString& pd)
-{
- zypp::Url url;
-
- try {
- url = zypp::Url(media->value ());
- }
- catch(const zypp::Exception & expt )
- {
- y2error ("Invalid URL: %s", expt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(expt));
- return YCPList();
- }
-
- zypp::Pathname pn(pd->value ());
-
- YCPList ids;
- std::vector<zypp::RepoInfo>::size_type id;
-
- if ( pd->value().empty() ) {
-
- // scan all sources
- zypp::MediaProductSet products;
-
- try
- {
- y2milestone("Scanning products in %s ...", url.asString().c_str());
- ScanProductsWithCallBacks(url);
- products = available_products;
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("Scanning products for '%s' has failed"
- , url.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- return ids;
- }
-
- if( products.empty() )
- {
- // no products found, use the base URL instead
- zypp::MediaProductEntry entry;
- products.insert(entry);
- }
-
- for( zypp::MediaProductSet::const_iterator it = products.begin();
- it != products.end() ; ++it )
- {
- try
- {
- y2milestone("Using product %s in directory %s", it->_name.c_str(), it->_dir.c_str());
- id = createManagedSource(url, it->_dir, false, "", it->_name);
- ids->add( YCPInteger(id) );
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("SourceScan for '%s' product '%s' has failed"
- , url.asString().c_str(), pn.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- }
- }
- } else {
- y2debug("Creating source...");
-
- try
- {
- id = createManagedSource(url, pn, false, "", "");
- ids->add( YCPInteger(id) );
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("SourceScan for '%s' product '%s' has failed"
- , url.asString().c_str(), pn.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- }
- }
-
- y2milestone("Found sources: %s", ids->toString().c_str() );
-
- return ids;
-}
-
-/****************************************************************************************
- * @builtin SourceCreate
- *
- * @short Create a Source
- * @description
- * Load and enable all InstSrces found at media_url, i.e. all sources mentioned in /media.1/products.
- * If no /media.1/products is available, InstSrc is expected to be located directly below
- * media_url (product_dir: /).
- *
- * If a product_dir is provided, only the InstSrc located at media_url/product_dir is loaded
- * and enabled.
- *
- * @param string url The media to scan.
- * @optarg string product_dir Restrict scan to a certain InstSrc located in media_url/product_dir.
- *
- * @return integer The source_id of the first InstSrc found on the media.
- **/
-YCPValue
-PkgModuleFunctions::SourceCreate (const YCPString& media, const YCPString& pd)
-{
- // not base product, autoprobe source type
- return SourceCreateEx (media, pd, false, YCPString(""));
-}
-
-YCPValue
-PkgModuleFunctions::SourceCreateBase (const YCPString& media, const YCPString& pd)
-{
- // base product, autoprobe source type
- return SourceCreateEx (media, pd, true, YCPString(""));
-}
-
-/**
- * @builtin SourceCreateType
- * @short Create source of required type
- * @description
- * Create a source without autoprobing the source type. This builtin should be used only for "Plaindir" sources, because Plaindir sources are not automatically probed in SourceCreate() builtin.
- * @param media URL of the source
- * @param pd product directory (if empty the products will be searched)
- * @param type type of the source ("YaST", "YUM" or "Plaindir")
-*/
-
-YCPValue
-PkgModuleFunctions::SourceCreateType (const YCPString& media, const YCPString& pd, const YCPString& type)
-{
- // not base product, autoprobe source type
- return SourceCreateEx (media, pd, false, type);
-}
-
-YCPValue
-PkgModuleFunctions::SourceCreateEx (const YCPString& media, const YCPString& pd, bool base, const YCPString& source_type)
-{
- y2debug("Creating source...");
-
- zypp::Pathname pn(pd->value ());
-
- zypp::Url url;
-
- try {
- url = zypp::Url(media->value ());
- }
- catch(const zypp::Exception & expt )
- {
- y2error ("Invalid URL: %s", expt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(expt));
- return YCPInteger (-1LL);
- }
-
-
- YCPList ids;
- std::vector<zypp::RepoInfo>::size_type ret = -1;
-
- const std::string type = source_type->value();
-
- if ( pd->value().empty() ) {
- // scan all sources
- zypp::MediaProductSet products;
-
- try {
- ScanProductsWithCallBacks(url);
- products = available_products;
- }
- catch ( const zypp::Exception& excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error( "Cannot read the product list from the media" );
- return YCPInteger(-1LL);
- }
-
- if( products.empty() )
- {
- // no products found, use the base URL instead
- zypp::MediaProductEntry entry ;
- products.insert( entry );
- }
-
- for( zypp::MediaProductSet::const_iterator it = products.begin();
- it != products.end() ; ++it )
- {
- try
- {
- std::vector<zypp::RepoInfo>::size_type id = createManagedSource(url, it->_dir, base, type, it->_name);
- YRepo_Ptr repo = logFindRepository(id);
-
- LoadResolvablesFrom(repo->repoInfo());
-
- // return the id of the first product
- if ( it == products.begin() )
- ret = id;
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("SourceCreate for '%s' product '%s' has failed"
- , url.asString().c_str(), pn.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- return YCPInteger(-1LL);
- }
- }
- } else {
- y2debug("Creating source...");
-
- try
- {
- ret = createManagedSource(url, pn, base, type, "");
-
- YRepo_Ptr repo = logFindRepository(ret);
- repo->repoInfo().setEnabled(true);
-
- LoadResolvablesFrom(repo->repoInfo());
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("SourceCreate for '%s' product '%s' has failed"
- , url.asString().c_str(), pn.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- }
- }
-
- PkgFreshen();
- return YCPInteger(repos.size() - 1);
-}
-
-
-/****************************************************************************************
- * @builtin SourceSetEnabled
- *
- * @short Set the default activation state of an InsrSrc.
- * @param integer SrcId Specifies the InstSrc.
- * @param boolean enabled Default activation state of source.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceSetEnabled (const YCPInteger& id, const YCPBoolean& e)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- // no change required
- bool enable = e->value();
- if ((enable && repo->repoInfo().enabled())
- || (!enable && !repo->repoInfo().enabled()))
- return YCPBoolean(true);
-
- bool success = true;
-
- try
- {
- repo->repoInfo().setEnabled(enable);
-
- // add/remove resolvables
- if (enable)
- {
- // load resolvables only when they are missing
- if (!AnyResolvableFrom(repo->repoInfo().alias()))
- {
- success = LoadResolvablesFrom(repo->repoInfo());
- }
- }
- else
- {
- // the source has been disabled, remove resolvables from the pool
- RemoveResolvablesFrom(repo->repoInfo().alias());
- }
-
- PkgFreshen();
- }
- catch (const zypp::Exception& excpt)
- {
- std::string alias = repo->repoInfo().alias();
- y2error ("Error for '%s': %s", alias.c_str(), excpt.asString().c_str());
- _last_error.setLastError(alias + ": " + ExceptionAsString(excpt));
- success = false;
- }
-
- return YCPBoolean(success);
-}
-
-/****************************************************************************************
- * @builtin SourceSetAutorefresh
- *
- * @short Set whether this source should automaticaly refresh it's
- * meta data when it gets enabled. (default true, if not CD/DVD)
- * @param integer SrcId Specifies the InstSrc.
- * @param boolean enabled Whether autorefresh should be turned on or off.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceSetAutorefresh (const YCPInteger& id, const YCPBoolean& e)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- repo->repoInfo().setAutorefresh(e->value());
-
- return YCPBoolean( true );
-}
-
-/****************************************************************************************
- * @builtin SourceFinish
- * @short Disable an Installation Source
- * @param integer SrcId Specifies the InstSrc.
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceFinish (const YCPInteger& id)
-{
- return SourceSetEnabled(id, false);
-}
-
-/****************************************************************************************
- * @builtin SourceRefreshNow
- * @short Attempt to immediately refresh a Source
- * @description
- * The InsrSrc will be encouraged to check and refresh all metadata
- * cached on disk.
- *
- * @param integer SrcId Specifies the InstSrc.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceRefreshNow (const YCPInteger& id)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- try
- {
- zypp::RepoManager repomanager = CreateRepoManager();
- y2milestone("Refreshing metadata '%s'", repo->repoInfo().alias().c_str());
- RefreshWithCallbacks(repo->repoInfo());
-
- y2milestone("Caching source '%s'...", repo->repoInfo().alias().c_str());
- repomanager.buildCache(repo->repoInfo());
- }
- catch ( const zypp::Exception & expt )
- {
- y2error ("Error while refreshing the source: %s", expt.asString().c_str());
- _last_error.setLastError(repo->repoInfo().alias() + ": " + ExceptionAsString(expt));
- return YCPBoolean(false);
- }
-
- return YCPBoolean( true );
-}
-
-/****************************************************************************************
- * @builtin SourceDelete
- * @short Delete a Source
- * @description
- * Delete an InsrSrc. The InsrSrc together with all metadata cached on disk
- * is removed. The SrcId passed becomes invalid (other SrcIds stay valid).
- *
- * @param integer SrcId Specifies the InstSrc.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceDelete (const YCPInteger& id)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- bool success = true;
-
- try
- {
- // the resolvables cannot be used anymore, remove them
- RemoveResolvablesFrom(repo->repoInfo().alias());
-
- // update 'repos'
- repo->setDeleted();
-
- PkgFreshen();
- }
- catch (const zypp::Exception& excpt)
- {
- std::string alias = repo->repoInfo().alias();
- y2error ("Error for '%s': %s", alias.c_str(), excpt.asString().c_str());
- _last_error.setLastError(alias + ": " + ExceptionAsString(excpt));
- success = false;
- }
-
- return YCPBoolean(success);
-}
-
-/****************************************************************************************
- * @builtin SourceEditGet
- *
- * @short Get state of Sources
- * @description
- * Return a list of states for all known InstSources sorted according to the
- * source priority (highest first). A source state is a map:
- * $[
- * "SrcId" : YCPInteger,
- * "enabled" : YCPBoolean
- * "autorefresh": YCPBoolean
- * ];
- *
- * @return list<map> list of source states (map)
- **/
-YCPValue
-PkgModuleFunctions::SourceEditGet ()
-{
- YCPList ret;
-
- unsigned long index = 0;
- for( std::vector<YRepo_Ptr>::const_iterator it = repos.begin(); it != repos.end(); ++it, ++index)
- {
- if (!(*it)->isDeleted())
- {
- YCPMap src_map;
-
- src_map->add(YCPString("SrcId"), YCPInteger(index));
- // Note: enabled() is tribool
- src_map->add(YCPString("enabled"), YCPBoolean((*it)->repoInfo().enabled()));
- // Note: autorefresh() is tribool
- src_map->add(YCPString("autorefresh"), YCPBoolean((*it)->repoInfo().autorefresh()));
- src_map->add(YCPString("name"), YCPString((*it)->repoInfo().name()));
-
- ret->add(src_map);
- }
- }
-
- return ret;
-}
-
-/****************************************************************************************
- * @builtin SourceEditSet
- *
- * @short Configure properties of installation sources
- * @description
- * Set states of installation sources. Note: Enabling/disabling a source does not
- * (un)load the packages from the source! Use SourceSetEnabled() if you need to refresh
- * the packages in the pool.
- *
- * @param list source_states List of source states. Same format as returned by
- * @see SourceEditGet.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceEditSet (const YCPList& states)
-{
- bool error = false;
-
- for (int index = 0; index < states->size(); index++ )
- {
- if( ! states->value(index)->isMap() )
- {
- ycperror( "Pkg::SourceEditSet, entry not a map at index %d", index);
- error = true;
- continue;
- }
-
- YCPMap descr = states->value(index)->asMap();
-
- if (descr->value( YCPString("SrcId") ).isNull() || !descr->value(YCPString("SrcId"))->isInteger())
- {
- ycperror( "Pkg::SourceEditSet, SrcId not defined for a source description at index %d", index);
- error = true;
- continue;
- }
-
- std::vector<YRepo_Ptr>::size_type id = descr->value( YCPString("SrcId") )->asInteger()->value();
-
- YRepo_Ptr repo = logFindRepository(id);
- if (!repo)
- {
- ycperror( "Pkg::SourceEditSet, source %d not found", index);
- error = true;
- continue;
- }
-
- // now, we have the source
- if( ! descr->value( YCPString("enabled")).isNull() && descr->value(YCPString("enabled"))->isBoolean ())
- {
- bool enable = descr->value(YCPString("enabled"))->asBoolean ()->value();
-
- if (repo->repoInfo().enabled() != enable)
- {
- ycpwarning("Pkg::SourceEditSet() does not refresh the pool (src: %zd, state: %s)", id, enable ? "disabled -> enabled" : "enabled -> disabled");
- }
-
- y2debug("set enabled: %d", enable);
- repo->repoInfo().setEnabled(enable);
- }
-
- if( !descr->value(YCPString("autorefresh")).isNull() && descr->value(YCPString("autorefresh"))->isBoolean ())
- {
- bool autorefresh = descr->value(YCPString("autorefresh"))->asBoolean()->value();
- y2debug("set autorefresh: %d", autorefresh);
- repo->repoInfo().setAutorefresh( autorefresh );
- }
-
- if( !descr->value(YCPString("name")).isNull() && descr->value(YCPString("name"))->isString())
- {
- // rename the source
- y2debug("set name: %s", descr->value(YCPString("name"))->asString()->value().c_str());
- repo->repoInfo().setName(descr->value(YCPString("name"))->asString()->value());
- }
-
-#warning SourceEditSet ordering not implemented yet
- }
-
- PkgFreshen();
- return YCPBoolean( !error );
-}
-
-/////////////////////////////////////////////////////////////////////////////////////////
-//
-// DEPRECATED
-//
-/////////////////////////////////////////////////////////////////////////////////////////
-
-/****************************************************************************************
- * Pkg::SourceRaisePriority (integer SrcId) -> bool
- *
- * Raise priority of source.
- *
- * @param SrcId Specifies the InstSrc.
- *
- * @return bool
- **/
-YCPValue
-PkgModuleFunctions::SourceRaisePriority (const YCPInteger& id)
-{
-#warning SourceRaisePriority is not implemented
- y2warning("SourceRaisePriority is NOT implemented");
-/* zypp::Source_Ref src;
-
- try {
- src = logFindRepository(id->value());
- }
- catch (const zypp::Exception& excpt)
- {
- return YCPBoolean(false);
- }
-
- // raise priority by one
- src.setPriority(src.priority() + 1);
-*/
-
- return YCPBoolean( true );
-
-}
-
-/****************************************************************************************
- * Pkg::SourceLowerPriority (integer SrcId) -> void
- *
- * Lower priority of source.
- *
- * @param SrcId Specifies the InstSrc.
- *
- * @return bool
- */
-YCPValue
-PkgModuleFunctions::SourceLowerPriority (const YCPInteger& id)
-{
-#warning SourceLowerPriority is not implemented
- y2warning("SourceLowerPriority is NOT implemented");
-/*
- zypp::Source_Ref src;
-
- try {
- src = logFindRepository(id->value());
- }
- catch (const zypp::Exception& excpt)
- {
- return YCPBoolean(false);
- }
-
- // lower priority by one
- src.setPriority(src.priority() - 1);
-*/
- return YCPBoolean( true );
-}
-
-/****************************************************************************************
- * Pkg::SourceSaveRanks () -> boolean
- *
- * @short Obsoleted function, do not use
- * @return boolean true
- **/
-YCPValue
-PkgModuleFunctions::SourceSaveRanks ()
-{
- y2error( "SourceSaveRanks not implemented" );
-
- return YCPBoolean( true );
-}
-
-/****************************************************************************************
- * @builtin SourceMoveDownloadArea
- *
- * @short Move download area of CURL-based sources to specified directory
- * @param path specifies the path to move the download area to
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceMoveDownloadArea (const YCPString & path)
-{
- try
- {
- y2milestone("Moving download area of all sources to %s", path->value().c_str());
- zypp::media::MediaManager manager;
- manager.setAttachPrefix(path->value());
- }
- catch (zypp::Exception & excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error("Pkg::SourceMoveDownloadArea has failed: %s", excpt.msg().c_str());
- return YCPBoolean(false);
- }
-
- y2milestone( "Download areas moved");
-
- return YCPBoolean(true);
-}
-
-/*
- * A helper function - remove all resolvables from the repository from the pool
- */
-void PkgModuleFunctions::RemoveResolvablesFrom(const std::string &alias)
-{
- // remove the resolvables if they have been loaded
- // FIXME: can be implemented better? we need a ResStore object for removing,
- // which means search for a resolvable in the pool and get the Repository
- // object which can be asked for all resolvables in it
- for (zypp::ResPool::const_iterator it = zypp_ptr()->pool().begin()
- ; it != zypp_ptr()->pool().end()
- ; ++it)
- {
- if (it->resolvable()->repository().info().alias() == alias)
- {
- y2milestone("Removing all resolvables from '%s' from the pool...", alias.c_str());
- zypp_ptr()->removeResolvables(it->resolvable()->repository().resolvables());
- break;
- }
- }
-}
-
-/*
- * A helper function - is there any resolvable from the repository in the pool?
- */
-bool PkgModuleFunctions::AnyResolvableFrom(const std::string &alias)
-{
- for (zypp::ResPool::const_iterator it = zypp_ptr()->pool().begin()
- ; it != zypp_ptr()->pool().end()
- ; ++it)
- {
- if (it->resolvable()->repository().info().alias() == alias)
- {
- return true;
- }
- }
-
- return false;
-}
-
-/*
- * A helper function - load resolvable from the repository into the pool
- * Warning: Use AnyResolvableFrom() method for checing if the resolvables might be already loaded
- */
-bool PkgModuleFunctions::LoadResolvablesFrom(const zypp::RepoInfo &repoinfo)
-{
- bool success = true;
- unsigned int size_start = zypp_ptr()->pool().size();
- y2milestone("Loading resolvables from '%s', pool size at start: %d", repoinfo.alias().c_str(), size_start);
-
- try
- {
- zypp::RepoManager repomanager = CreateRepoManager();
-
- // build cache if needed
- if (!repomanager.isCached(repoinfo))
- {
- zypp::RepoStatus raw_metadata_status = repomanager.metadataStatus(repoinfo);
- if (raw_metadata_status.empty())
- {
- y2milestone("Missing metadata for source '%s', downloading...", repoinfo.alias().c_str());
- RefreshWithCallbacks(repoinfo);
- }
-
- y2milestone("Caching source '%s'...", repoinfo.alias().c_str());
- repomanager.buildCache(repoinfo);
- }
-
- zypp::Repository repository = repomanager.createFromCache(repoinfo);
- const zypp::ResStore &store = repository.resolvables();
-
- // load resolvables
- zypp_ptr()->addResolvables(store);
-
- y2milestone("Loaded %zd resolvables", store.size());
- }
- catch(const zypp::repo::RepoNotCachedException &excpt )
- {
- std::string alias = repoinfo.alias();
- y2error ("Resolvables from '%s' havn't been loaded: %s", alias.c_str(), excpt.asString().c_str());
- _last_error.setLastError("'" + alias + "': " + ExceptionAsString(excpt));
- success = false;
-
- // FIXME ??
- /*
- // disable the source
- y2error("Disabling source %s", url.c_str());
- repo->disable();
- */
- }
- catch (const zypp::Exception& excpt)
- {
- std::string alias = repoinfo.alias();
- y2internal("Error: Loading resolvables failed: %s", ExceptionAsString(excpt).c_str());
- _last_error.setLastError("'" + alias + "': " + ExceptionAsString(excpt));
- success = false;
- }
-
- unsigned int size_end = zypp_ptr()->pool().size();
- y2milestone("Pool size at end: %d (loaded %d resolvables)", size_end, size_end - size_start);
- return success;
-}
-
-/****************************************************************************************
- * @builtin RepositoryProbe
- *
- * @short Probe type of the repository
- * @param url specifies the path to the repository
- * @param prod_dir product directory (if empty the url is probed directly)
- * @return string repository type ("NONE" if type could be determined, nil if an error occurred (e.g. resolving the hostname)
- **/
-YCPValue PkgModuleFunctions::RepositoryProbe(const YCPString& url, const YCPString& prod_dir)
-{
- y2milestone("Probing repository type: '%s'...", url->value().c_str());
- zypp::RepoManager repomanager = CreateRepoManager();
- std::string ret;
-
- try
- {
- zypp::Url probe_url(url->value());
-
- // add the product directory
- std::string prod = prod_dir->value();
-
- if (!prod.empty())
- {
- // add "/" at the begining if it's missing
- if (std::string(prod, 0, 1) != "/")
- {
- prod = "/" + prod;
- }
-
- // merge the URL path and the product path
- std::string path = probe_url.getPathName();
- path += prod;
-
- y2milestone("Using probing path: %s", path.c_str());
- probe_url.setPathName(path);
- }
-
- // add "ro" mount option
- probe_url = addRO(probe_url);
-
- // autoprobe type of the repository
- zypp::repo::RepoType repotype = ProbeWithCallbacks(probe_url);
-
- ret = zypp2yastType(repotype.asString());
- y2milestone("Detected type: '%s'...", ret.c_str());
- }
- catch (const zypp::Exception& excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error( "Cannot detect the repository type" );
- return YCPVoid();
- }
-
- return YCPString(ret);
-}
-
-/****************************************************************************************
- * @builtin RepositoryScan
- *
- * @short Scan available products in the repository
- * @param url specifies the path to the repository
- * @return list<list<string>> list of the products: [ [ <product_name_1> <directory_1> ], ...]
- **/
-YCPValue PkgModuleFunctions::RepositoryScan(const YCPString& url)
-{
- zypp::MediaProductSet products;
-
- try
- {
- zypp::Url baseurl(url->value());
-
- baseurl = addRO(baseurl);
-
- ScanProductsWithCallBacks(baseurl);
- products = available_products;
- }
- catch ( const zypp::Exception& excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error( "Cannot read the product list from the media" );
- return YCPList();
- }
-
- YCPList ret;
-
- for( zypp::MediaProductSet::const_iterator it = products.begin();
- it != products.end() ; ++it )
- {
- YCPList prod;
-
- // add product directory
- prod.add(YCPString(it->_name));
- // add product name
- prod.add(YCPString(it->_dir.asString()));
-
- ret.add(prod);
- }
-
- y2milestone("Found products: %s", ret->toString().c_str());
-
- return ret;
-}
-
-// convert libzypp type to yast strings ("YaST", "YUM" or "Plaindir")
-std::string PkgModuleFunctions::zypp2yastType(const std::string &type)
-{
- std::string ret(type);
-
- if (type_conversion_table.empty())
- {
- // initialize the conversion map
- type_conversion_table["rpm-md"] = "YUM";
- type_conversion_table["yast2"] = "YaST";
- type_conversion_table["plaindir"] = "Plaindir";
- type_conversion_table["NONE"] = "NONE";
- }
-
- std::map<std::string,std::string>::const_iterator it = type_conversion_table.find(type);
-
- // found in the conversion table
- if (it != type_conversion_table.end())
- {
- ret = it->second;
- }
- else
- {
- y2error("Cannot convert type '%s'", type.c_str());
- }
+ // use the shorter path
+ ret.setPathName(new_path);
+ // remove query parameters
+ ret.setQueryString("");
+ // remove fragmet
+ ret.setFragment("");
+ y2milestone("Using shortened URL: '%s' -> '%s'", url.asString().c_str(), ret.asString().c_str());
return ret;
}
-std::string PkgModuleFunctions::yast2zyppType(const std::string &type)
-{
- // do conversion from the Yast type ("YaST", "YUM", "Plaindir")
- // to libzypp type ("yast", "yum", "plaindir")
- // we can simply use toLower instead of a conversion table
- // in this case
- return zypp::str::toLower(type);
-}
-
Copied: trunk/pkg-bindings/src/Source_Resolvables.cc (from r42708, trunk/pkg-bindings/src/Source.cc)
URL: http://svn.opensuse.org/viewcvs/yast/trunk/pkg-bindings/src/Source_Resolvab…
==============================================================================
--- trunk/pkg-bindings/src/Source.cc (original)
+++ trunk/pkg-bindings/src/Source_Resolvables.cc Thu Dec 6 07:56:58 2007
@@ -1,2698 +1,34 @@
-/*---------------------------------------------------------------------\
-| |
-| __ __ ____ _____ ____ |
-| \ \ / /_ _/ ___|_ _|___ \ |
-| \ V / _` \___ \ | | __) | |
-| | | (_| |___) || | / __/ |
-| |_|\__,_|____/ |_| |_____| |
-| |
-| core system |
-| (C) SuSE GmbH |
-\----------------------------------------------------------------------/
-
- File: PkgModuleFunctionsSource.cc
-
- Author: Klaus Kaempf <kkaempf(a)suse.de>
- Maintainer: Klaus Kaempf <kkaempf(a)suse.de>
-
- Summary: Access to Installation Sources
- Namespace: Pkg
- Purpose: Access to InstSrc
- Handles source related Pkg::function (list_of_arguments) calls
- from WFMInterpreter.
-/-*/
-//#include <unistd.h>
-//#include <sys/statvfs.h>
-
-#include <iostream>
-
-#include <ycpTools.h>
-#include <PkgModule.h>
-#include <PkgModuleFunctions.h>
-
-#include <Callbacks.h>
-#include <Callbacks.YCP.h>
-
-#include <zypp/Product.h>
-#include <zypp/media/MediaManager.h>
-#include <zypp/media/Mount.h>
-#include <zypp/Pathname.h>
-
-#include <zypp/RepoInfo.h>
-#include <zypp/RepoManager.h>
-#include <zypp/Fetcher.h>
-#include <zypp/repo/RepoType.h>
-#include <zypp/MediaProducts.h>
-#include <zypp/ExternalProgram.h>
-#include <zypp/ProgressData.h>
-
-#include <sstream> // ostringstream
-
-#include <PkgProgress.h>
-
-/*
- Textdomain "pkg-bindings"
-*/
-
-// scanned available products
-// hack: zypp/MediaProducts.h cannot be included in PkgModuleFunctions.h
-zypp::MediaProductSet available_products;
-
-// this method should be used instead of zypp::productsInMedia()
-// it initializes the download callbacks
-void PkgModuleFunctions::ScanProductsWithCallBacks(const zypp::Url &url)
-{
- CallInitDownload(std::string(_("Scanning products in ") + url.asString()));
-
- extern ZyppRecipients::MediaChangeSensitivity _silent_probing;
- // remember the current value
- ZyppRecipients::MediaChangeSensitivity _silent_probing_old = _silent_probing;
-
- // disable media change callback for optional file
- _silent_probing = ZyppRecipients::MEDIA_CHANGE_DISABLE;
-
- y2milestone("Scanning products in %s ...", url.asString().c_str());
-
- try
- {
- available_products.clear();
- zypp::productsInMedia(url, available_products);
- }
- catch(...)
- {
- // call the final event even in case of exception
- CallDestDownload();
-
- // restore the probing flag
- _silent_probing = _silent_probing_old;
-
- // rethrow the execption
- throw;
- }
-
- CallDestDownload();
-
- // restore the probing flag
- _silent_probing = _silent_probing_old;
-}
-
-void PkgModuleFunctions::CallSourceReportStart(const std::string &text)
-{
- // get the YCP callback handler
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_SourceReportStart);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- // add parameters
- ycp_handler->appendParameter( YCPInteger(0LL) );
- ycp_handler->appendParameter( YCPString("") );
- ycp_handler->appendParameter( YCPString(text) );
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-
-void PkgModuleFunctions::CallSourceReportEnd(const std::string &text)
-{
- // get the YCP callback handler for end event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_SourceReportEnd);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- // add parameters
- ycp_handler->appendParameter( YCPInteger(0LL) );
- ycp_handler->appendParameter( YCPString("") );
- ycp_handler->appendParameter( YCPString(text) );
- ycp_handler->appendParameter( YCPString("NO_ERROR") );
- ycp_handler->appendParameter( YCPString("") );
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-
-void PkgModuleFunctions::CallSourceReportInit()
-{
- // get the YCP callback handler for init event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_SourceReportInit);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-
-void PkgModuleFunctions::CallSourceReportDestroy()
-{
- // get the YCP callback handler for destroy event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_SourceReportDestroy);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-
-void PkgModuleFunctions::CallInitDownload(const std::string &task)
-{
- // get the YCP callback handler for destroy event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_InitDownload);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- ycp_handler->appendParameter(YCPString(task));
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-
-void PkgModuleFunctions::CallDestDownload()
-{
- // get the YCP callback handler for destroy event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_DestDownload);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-
-// this method should be used instead of RepoManager::refreshMetadata()
-void PkgModuleFunctions::RefreshWithCallbacks(const zypp::RepoInfo &repo)
-{
- CallInitDownload(std::string(_("Refreshing repository ") + repo.alias()));
-
- try
- {
- zypp::RepoManager repomanager = CreateRepoManager();
- repomanager.refreshMetadata(repo);
- }
- catch(...)
- {
- // call the final event even in case of exception
- CallDestDownload();
- // rethrow the execption
- throw;
- }
-
- CallDestDownload();
-}
-
-// this method should be used instead of RepoManager::probe()
-zypp::repo::RepoType PkgModuleFunctions::ProbeWithCallbacks(const zypp::Url &url)
-{
- CallInitDownload(std::string(_("Probing repository ") + url.asString()));
-
- zypp::repo::RepoType repotype;
-
- extern ZyppRecipients::MediaChangeSensitivity _silent_probing;
- // remember the current value
- ZyppRecipients::MediaChangeSensitivity _silent_probing_old = _silent_probing;
-
- // disable media change callback for optional file
- _silent_probing = ZyppRecipients::MEDIA_CHANGE_DISABLE;
-
- try
- {
- // probe type of the repository
- zypp::RepoManager repomanager = CreateRepoManager();
- repotype = repomanager.probe(url);
- }
- catch(...)
- {
- // call the final event even in case of exception
- CallDestDownload();
-
- // restore the probing flag
- _silent_probing = _silent_probing_old;
-
- // rethrow the execption
- throw;
- }
-
- CallDestDownload();
-
- // restore the probing flag
- _silent_probing = _silent_probing_old;
-
- return repotype;
-}
-
-/**
- * Logging helper:
- * call zypp::SourceManager::sourceManager()->findSource
- * and in case of exception, log error and setLastError AND RETHROW
- */
-YRepo_Ptr PkgModuleFunctions::logFindRepository(std::vector<YRepo_Ptr>::size_type id)
-{
- try
- {
- if (id < 0 || id >= repos.size())
- {
- // not found
- throw(std::exception());
- }
-
- if (!repos[id])
- {
- // not found
- throw(std::exception());
- }
-
- if (repos[id]->isDeleted())
- {
- y2error("Source %zd has been deleted, the ID is not valid", id);
- return YRepo_Ptr();
- }
-
- return repos[id];
- }
- catch (...)
- {
- y2error("Cannot find source with ID: %zd", id);
- // TODO: improve the error message
- _last_error.setLastError(_("Cannot find source"));
- }
-
- // not found, return empty pointer
- return YRepo_Ptr();
-}
-
-long long PkgModuleFunctions::logFindAlias(const std::string &alias) const
-{
- std::vector<YRepo_Ptr>::size_type index = 0;
-
- for(std::vector<YRepo_Ptr>::const_iterator it = repos.begin(); it != repos.end() ; ++it, ++index)
- {
- if (!(*it)->isDeleted() && (*it)->repoInfo().alias() == alias)
- return index;
- }
-
- return -1LL;
-}
-
-bool PkgModuleFunctions::aliasExists(const std::string &alias) const
-{
- for(std::vector<YRepo_Ptr>::const_iterator it = repos.begin(); it != repos.end() ; ++it)
- {
- if (!(*it)->isDeleted() && (*it)->repoInfo().alias() == alias)
- return true;
- }
-
- return false;
-}
-
-/****************************************************************************************
- * @builtin SourceSetRamCache
- * @short Obsoleted function, do not use
- * @param boolean
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceSetRamCache (const YCPBoolean& a)
-{
- y2warning( "Pkg::SourceSetRamCache is obsolete and does nothing");
- return YCPBoolean( true );
-}
-
-
-/****************************************************************************************
- * @builtin SourceRestore
- *
- * @short Restore the sources from the persistent store
- * @description
- * Make sure the Source Manager is up and knows all available installation sources.
- * It's safe to call this multiple times, and once the installation sources are
- * actually enabled, it's even cheap
- *
- * @return boolean True on success
- **/
-YCPValue
-PkgModuleFunctions::SourceRestore()
-{
- if (repos.size() > 0)
- {
- y2warning("Number of registered repositories: %zd, skipping repository load!", repos.size());
- return YCPBoolean(true);
- }
-
- bool success = true;
-
- try
- {
- zypp::RepoManager repomanager = CreateRepoManager();
- std::list<zypp::RepoInfo> reps = repomanager.knownRepositories();
-
- repos.clear();
- for (std::list<zypp::RepoInfo>::iterator it = reps.begin();
- it != reps.end(); ++it)
- {
- repos.push_back(new YRepo(*it));
- }
- }
- catch (const zypp::Exception& excpt)
- {
- // FIXME: assuming the sources are already initialized
- y2error ("Error in SourceRestore: %s", excpt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- success = false;
- }
-
- return YCPBoolean(success);
-}
-
-/****************************************************************************************
- * @builtin SourceGetBrokenSources
- *
- * @short Return list of broken sources (sources which failed to restore)
- * @description
- * Get list of all sources which could not have been restored.
- * @return list<string> list of aliases (product names or URLs)
- **/
-YCPValue PkgModuleFunctions::SourceGetBrokenSources()
-{
- y2warning("Pkg::SourceGetBrokenSources() is obsoleted, it's not needed anymore.");
- return YCPList();
-}
-
-bool PkgModuleFunctions::SourceLoadReceiver(const zypp::ProgressData &progress)
-{
- y2milestone("Source Load receiver: %lld (%lld%%)", progress.val(), progress.reportValue());
-
- // get the YCP callback handler for destroy event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_ProcessProgress);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- ycp_handler->appendParameter(YCPInteger(progress.reportValue()));
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-
- return true;
-}
-
-/****************************************************************************************
- * @builtin SourceLoad
- *
- * @short Load resolvables from the installation sources
- * @description
- * Refresh the pool - Add/remove resolvables from the enabled/disabled sources.
- * @return boolean True on success
- **/
-YCPValue
-PkgModuleFunctions::SourceLoad()
-{
- std::list<std::string> stages;
- stages.push_back("Refresh Sources");
- stages.push_back("Rebuild Cache");
- stages.push_back("Load Data");
-
- PkgProgress pkgprogress(_callbackHandler);
-
- // 3 steps per repository (download, cache rebuild, load resolvables)
- pkgprogress.Start("Loading the Package Manager...", stages, "help");
-
- YCPValue ret = SourceLoadImpl(pkgprogress);
-
- pkgprogress.Done();
-
- return ret;
-}
-
-
-/****************************************************************************************
- * @builtin SourceLoad
- *
- * @short Load resolvables from the installation sources
- * @description
- * Refresh the pool - Add/remove resolvables from the enabled/disabled sources.
- * @return boolean True on success
- **/
-YCPValue
-PkgModuleFunctions::SourceLoadImpl(PkgProgress &progress)
-{
- bool success = true;
-
- int repos_to_load = 0;
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
- {
- repos_to_load++;
- }
- }
-
- // set max. value (3 steps per repository - refresh, rebuild, load)
- zypp::ProgressData prog_total(repos_to_load * 3);
- prog_total.sendTo(progress.Receiver());
-
- zypp::RepoManager repomanager = CreateRepoManager();
-
- // refresh metadata
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- // load resolvables only from enabled repos which are not deleted
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
- {
- // sub tasks
- zypp::CombinedProgressData refresh_subprogress(prog_total, 1);
-
- if (AnyResolvableFrom((*it)->repoInfo().alias()))
- {
- y2milestone("Resolvables from '%s' are already present, not loading", (*it)->repoInfo().alias().c_str());
- }
- else
- {
- // autorefresh the source
- if ((*it)->repoInfo().autorefresh())
- {
- try
- {
- y2milestone("Autorefreshing source: %s", (*it)->repoInfo().alias().c_str());
- RefreshWithCallbacks((*it)->repoInfo());
-
- zypp::ProgressData prog(1);
- prog.sendTo(refresh_subprogress);
- RefreshWithCallbacks((*it)->repoInfo());
- prog.toMax();
- }
- // NOTE: subtask progresses are reported as done in the descructor
- // no need to handle them in the exception code
- catch (const zypp::Exception& excpt)
- {
- y2error ("Error in SourceLoad: %s", excpt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- success = false;
- }
- }
- }
- }
- }
-
- progress.NextStage();
-
- // rebuild cache
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- // load resolvables only from enabled repos which are not deleted
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
- {
- // sub tasks
- zypp::CombinedProgressData rebuild_subprogress(prog_total, 1);
-
- if (AnyResolvableFrom((*it)->repoInfo().alias()))
- {
- y2milestone("Resolvables from '%s' are already present, not loading", (*it)->repoInfo().alias().c_str());
- }
- else
- {
- // autorefresh the source
- if ((*it)->repoInfo().autorefresh())
- {
- try
- {
- // rebuild cache (the default policy is "if needed")
- y2milestone("Rebuilding cache for '%s'...", (*it)->repoInfo().alias().c_str());
-
- zypp::ProgressData prog(1);
- prog.sendTo(rebuild_subprogress);
- repomanager.buildCache((*it)->repoInfo());
- prog.toMax();
- }
- // NOTE: subtask progresses are reported as done in the descructor
- // no need to handle them in the exception code
- catch (const zypp::Exception& excpt)
- {
- y2error ("Error in SourceLoad: %s", excpt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- success = false;
- }
- }
- }
- }
- }
-
- progress.NextStage();
-
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- // load resolvables only from enabled repos which are not deleted
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
- {
- // sub tasks
- zypp::CombinedProgressData load_subprogress(prog_total, 1);
-
- if (AnyResolvableFrom((*it)->repoInfo().alias()))
- {
- y2milestone("Resolvables from '%s' are already present, not loading", (*it)->repoInfo().alias().c_str());
- }
- else
- {
- zypp::ProgressData prog(1);
- prog.sendTo(load_subprogress);
-
- // load objects
- success = LoadResolvablesFrom((*it)->repoInfo()) && success;
-
- prog.toMax();
- }
- }
- }
-
- // report 100%
- prog_total.toMax();
-
- return YCPBoolean(success);
-}
-
-
-/****************************************************************************************
- * @builtin SourceStartManager
- *
- * @short Start the source manager - restore the sources and load the resolvables
- * @description
- * Calls SourceRestore(), if argument enable is true SourceLoad() is called.
- * @param boolean enable If true the resolvables are loaded from the enabled sources
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceStartManager (const YCPBoolean& enable)
-{
- PkgProgress pkgprogress(_callbackHandler);
-
- // display the progress only when 'enable' is true
- if (enable->value())
- {
- std::list<std::string> stages;
- stages.push_back("Load Sources");
- stages.push_back("Refresh Sources");
- stages.push_back("Rebuild Cache");
- stages.push_back("Load Data");
-
- // 3 steps per repository (download, cache rebuild, load resolvables)
- pkgprogress.Start("Loading the Package Manager...", stages, "help");
- }
-
- YCPValue ret = SourceStartManagerImpl(enable, pkgprogress);
-
- if (enable->value())
- {
- pkgprogress.Done();
- }
-
- return ret;
-}
-
-/****************************************************************************************
- * @builtin SourceStartManager
- *
- * @short Start the source manager - restore the sources and load the resolvables
- * @description
- * Calls SourceRestore(), if argument enable is true SourceLoad() is called.
- * @param boolean enable If true the resolvables are loaded from the enabled sources
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceStartManagerImpl(const YCPBoolean& enable, PkgProgress &progress)
-{
- YCPValue success = SourceRestore();
-
- progress.NextStage();
-
- if( enable->value() )
- {
- if (!success->asBoolean()->value())
- {
- y2warning("SourceStartManager: Some sources have not been restored, loading only the active sources...");
- }
-
- // enable all sources and load the resolvables
- success = YCPBoolean(SourceLoadImpl(progress)->asBoolean()->value() && success->asBoolean()->value());
- }
-
- return success;
-}
-
-/****************************************************************************************
- * @builtin SourceStartCache
- *
- * @short Make sure the InstSrcManager is up, and return the list of SrcIds.
- * @description
- * Make sure the InstSrcManager is up, and return the list of SrcIds.
- * In fact nothing more than:
- *
- * <code>
- * SourceStartManager( enabled_only );
- * return SourceGetCurrent( enabled_only );
- * </code>
- *
- * @param boolean enabled_only If true, make sure all InstSrces are enabled according to
- * their default, and return the Ids of enabled InstSrces only. If false, return
- * the Ids of all known InstSrces.
- *
- * @return list<integer> list of SrcIds
- **/
-YCPValue
-PkgModuleFunctions::SourceStartCache (const YCPBoolean& enabled)
-{
- try
- {
- SourceStartManager(enabled);
-
- return SourceGetCurrent(enabled);
- }
- catch (const zypp::Exception& excpt)
- {
- y2error ("Error in SourceStartCache: %s", excpt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- }
- // catch an exception from boost (e.g. a file cannot be read by non-root user)
- catch (const std::exception& err)
- {
- y2error ("Error in SourceStartCache: %s", err.what());
- _last_error.setLastError(err.what());
- }
- catch (...)
- {
- y2error("Unknown error in SourceStartCache");
- }
-
- return YCPList();
-}
-
-/****************************************************************************************
- * @builtin SourceCleanupBroken
- *
- * @short Clean up all sources that were not properly restored on the last
- * call of SourceStartManager or SourceStartCache.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceCleanupBroken ()
-{
- y2warning("Pkg::SourceCleanupBroken() is obsoleted, it's not needed anymore.");
- return YCPBoolean(true);
-}
-
-/****************************************************************************************
- * @builtin SourceGetCurrent
- *
- * @short Return the list of all InstSrc Ids.
- *
- * @param boolean enabled_only If true, or omitted, return the Ids of all enabled InstSrces.
- * If false, return the Ids of all known InstSrces.
- *
- * @return list<integer> list of SrcIds (integer)
- **/
-YCPValue
-PkgModuleFunctions::SourceGetCurrent (const YCPBoolean& enabled)
-{
- YCPList res;
-
- std::vector<YRepo_Ptr>::size_type index = 0;
- for( std::vector<YRepo_Ptr>::const_iterator it = repos.begin(); it != repos.end() ; ++it, ++index )
- {
- // ignore disabled sources if requested
- if (enabled->value())
- {
- // Note: enabled() is tribool!
- if ((*it)->repoInfo().enabled())
- {
- }
- else if (!(*it)->repoInfo().enabled())
- {
- continue;
- }
- else
- {
- continue;
- }
- }
-
- // ignore deleted sources
- if ((*it)->isDeleted())
- {
- continue;
- }
-
- res->add( YCPInteger(index) );
- }
-
- return res;
-}
-
-/****************************************************************************************
- * @builtin SourceReleaseAll
- *
- * @short Release all medias hold by all sources
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceReleaseAll ()
-{
- y2milestone("Releasing all sources...");
- bool ret = true;
-
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- try
- {
- (*it)->mediaAccess()->release();
- }
- catch (const zypp::media::MediaException & ex)
- {
- y2warning("Failed to release media for repo: %s", ex.msg().c_str());
- ret = false;
- }
- }
-
- return YCPBoolean(ret);
-}
-
-/******************************************************************************
- * @builtin SourceSaveAll
- *
- * @short Save all InstSrces.
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceSaveAll ()
-{
- y2milestone("Saving the source setup...");
-
- zypp::RepoManager repomanager = CreateRepoManager();
-
- // remove deleted repos (the old configurations) at first
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- // the repo has been removed
- if ((*it)->isDeleted())
- {
- std::string repo_alias = (*it)->repoInfo().alias();
-
- try
- {
- // remove the metadata
- zypp::RepoStatus raw_metadata_status = repomanager.metadataStatus((*it)->repoInfo());
- if (!raw_metadata_status.empty())
- {
- y2milestone("Removing metadata for source '%s'...", repo_alias.c_str());
- repomanager.cleanMetadata((*it)->repoInfo());
- }
-
- // remove the cache
- if (repomanager.isCached((*it)->repoInfo()))
- {
- y2milestone("Removing cache for '%s'...", repo_alias.c_str());
- repomanager.cleanCache((*it)->repoInfo());
- }
-
- repomanager.getRepositoryInfo(repo_alias);
- y2milestone("Removing repository '%s'", repo_alias.c_str());
- repomanager.removeRepository((*it)->repoInfo());
- }
- catch (const zypp::repo::RepoNotFoundException &ex)
- {
- // repository not found -- not critical, continue
- y2warning("No such repository: %s", repo_alias.c_str());
- }
- catch (const zypp::Exception & excpt)
- {
- y2error("Pkg::SourceSaveAll has failed: %s", excpt.msg().c_str() );
- _last_error.setLastError(ExceptionAsString(excpt));
- return YCPBoolean(false);
- }
- }
- }
-
- // save all repos (the current configuration)
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- if (!(*it)->isDeleted())
- {
- std::string current_alias = (*it)->repoInfo().alias();
-
- try
- {
- try
- {
- // if the repository already exists then just modify it
- repomanager.getRepositoryInfo(current_alias);
- y2milestone("Modifying repository '%s'", current_alias.c_str());
- repomanager.modifyRepository(current_alias, (*it)->repoInfo());
- }
- catch (const zypp::repo::RepoNotFoundException &ex)
- {
- // the repository was not found, add it
- y2milestone("Adding repository '%s'", current_alias.c_str());
- repomanager.addRepository((*it)->repoInfo());
- }
- }
- catch (zypp::Exception & excpt)
- {
- y2error("Pkg::SourceSaveAll has failed: %s", excpt.msg().c_str() );
- _last_error.setLastError(ExceptionAsString(excpt));
- return YCPBoolean(false);
- }
- }
- }
-
- y2milestone("All sources have been saved");
-
- return YCPBoolean(true);
-}
-
-/****************************************************************************************
- * @builtin SourceFinishAll
- *
- * @short Save and then disable all InstSrces.
- * @description
- * If there are no enabled sources, do nothing
- * (idempotence hack, broken design: #155459, #176013, use SourceSaveAll).
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceFinishAll ()
-{
- try
- {
- bool found_enabled = false;
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
- {
- found_enabled = true;
- break;
- }
- }
-
- if (!found_enabled)
- {
- y2milestone( "No enabled sources, skipping SourceFinishAll()" );
- return YCPBoolean( true );
- }
-
- SourceSaveAll();
-
- y2milestone( "Disabling all sources...") ;
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- (*it)->repoInfo().setEnabled(false);
- }
- // TODO FIXME remove all resolvables??
- }
- catch (zypp::Exception & excpt)
- {
- y2error("Pkg::SourceFinishAll has failed: %s", excpt.msg().c_str() );
- _last_error.setLastError(ExceptionAsString(excpt));
- return YCPBoolean(false);
- }
-
- y2milestone("All sources have been saved and disabled");
-
- return YCPBoolean(true);
-}
-
-/////////////////////////////////////////////////////////////////////////////////////////
-// Query individual sources
-/////////////////////////////////////////////////////////////////////////////////////////
-
-/****************************************************************************************
- * @builtin SourceGeneralData
- *
- * @short Get general data about the source
- * @description
- * Return general data about the source as a map:
- *
- * <code>
- * $[
- * "enabled" : YCPBoolean,
- * "autorefresh": YCPBoolean,
- * "product_dir": YCPString,
- * "type" : YCPString,
- * "url" : YCPString (without password, but see SourceURL),
- * "alias" : YCPString,
- * "name" : YCPString,
- * ];
- *
- * </code>
- * @param integer SrcId Specifies the InstSrc to query.
- * @return map
- **/
-YCPValue
-PkgModuleFunctions::SourceGeneralData (const YCPInteger& id)
-{
- YCPMap data;
-
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPVoid ();
-
- // convert type to the old strings ("YaST", "YUM" or "Plaindir")
- std::string srctype = zypp2yastType(repo->repoInfo().type().asString());
-
- data->add( YCPString("enabled"), YCPBoolean(repo->repoInfo().enabled()));
- data->add( YCPString("autorefresh"), YCPBoolean(repo->repoInfo().autorefresh()));
- data->add( YCPString("type"), YCPString(srctype));
- data->add( YCPString("product_dir"), YCPString(repo->repoInfo().path().asString()));
-
- // check if there is an URL
- if (repo->repoInfo().baseUrlsBegin() != repo->repoInfo().baseUrlsEnd())
- {
- data->add( YCPString("url"), YCPString(repo->repoInfo().baseUrlsBegin()->asString()));
- }
-
- data->add( YCPString("alias"), YCPString(repo->repoInfo().alias()));
- data->add( YCPString("name"), YCPString(repo->repoInfo().name()));
-
- YCPList base_urls;
- for( zypp::RepoInfo::urls_const_iterator it = repo->repoInfo().baseUrlsBegin(); it != repo->repoInfo().baseUrlsEnd(); ++it)
- {
- base_urls->add(YCPString(it->asString()));
- }
- data->add( YCPString("base_urls"), base_urls);
-
- data->add( YCPString("mirror_list"), YCPString(repo->repoInfo().mirrorListUrl().asString()));
-
- return data;
-}
-
-/******************************************************************************
- * @builtin SourceURL
- *
- * @short Get full source URL, including password
- * @param integer SrcId Specifies the InstSrc to query.
- * @return string or nil on failure
- **/
-YCPValue
-PkgModuleFunctions::SourceURL (const YCPInteger& id)
-{
-
- const YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPVoid();
-
- std::string url;
-
- if (repo->repoInfo().baseUrlsBegin() != repo->repoInfo().baseUrlsEnd())
- {
- // #186842
- url = repo->repoInfo().baseUrlsBegin()->asCompleteString();
- }
-
- return YCPString(url);
-}
-
-/****************************************************************************************
- * @builtin SourceMediaData
- * @short Return media data about the source
- * @description
- * Return media data about the source as a map:
- *
- * <code>
- * $["media_count": YCPInteger,
- * "media_id" : YCPString,
- * "media_vendor" : YCPString,
- * "url" : YCPString,
- * ];
- * </code>
- *
- * @param integer SrcId Specifies the InstSrc to query.
- * @return map
- **/
-YCPValue
-PkgModuleFunctions::SourceMediaData (const YCPInteger& id)
-{
- YCPMap data;
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPVoid ();
-
- std::string alias = repo->repoInfo().alias();
- bool found_resolvable = false;
- int max_medium = 1;
-
- for (zypp::ResPool::const_iterator it = zypp_ptr()->pool().begin()
- ; it != zypp_ptr()->pool().end()
- ; ++it)
- {
- if (it->resolvable()->repository().info().alias() == alias)
- {
- int medium = it->resolvable()->mediaNr();
-
- if (medium > max_medium)
- {
- max_medium = medium;
- }
- }
- }
-
- if (found_resolvable)
- {
- data->add( YCPString("media_count"), YCPInteger(max_medium));
- }
- else
- {
- y2error("No resolvable from repository '%s' found, cannot get number of media (use Pkg::SourceLoad() to load the resolvables)", alias.c_str());
- }
-
- y2warning("Pkg::SourceMediaData() doesn't return \"media_id\" and \"media_vendor\" values anymore.");
-
- // SourceMediaData returns URLs without password
- if (repo->repoInfo().baseUrlsBegin() != repo->repoInfo().baseUrlsEnd())
- {
- data->add( YCPString("url"), YCPString(repo->repoInfo().baseUrlsBegin()->asString()));
-
- // add all base URLs
- YCPList base_urls;
- for( zypp::RepoInfo::urls_const_iterator it = repo->repoInfo().baseUrlsBegin(); it != repo->repoInfo().baseUrlsEnd(); ++it)
- {
- base_urls->add(YCPString(it->asString()));
- }
- data->add( YCPString("base_urls"), base_urls);
- }
-
- return data;
-}
-
-/****************************************************************************************
- * @builtin SourceProductData
- * @short Return Product data about the source
- * @param integer SrcId Specifies the InstSrc to query.
- * @description
- * Product data about the source as a map:
- *
- * <code>
- * $[
- * "label" : YCPString,
- * "vendor" : YCPString,
- * "productname" : YCPString,
- * "productversion" : YCPString,
- * "relnotesurl" : YCPString,
- * ];
- * </code>
- *
- * @return map
- **/
-YCPValue
-PkgModuleFunctions::SourceProductData (const YCPInteger& src_id)
-{
- YCPMap ret;
-
- try
- {
- // find a product for the given source
- zypp::ResPool::byKind_iterator it = zypp_ptr()->pool().byKindBegin(zypp::ResTraits<zypp::Product>::kind);
-
- for( ; it != zypp_ptr()->pool().byKindEnd(zypp::ResTraits<zypp::Product>::kind) ; ++it)
- {
- zypp::Product::constPtr product = boost::dynamic_pointer_cast<const zypp::Product>( it->resolvable() );
-
- if( logFindAlias(product->repository().info().alias()) == src_id->value() )
- {
- ret->add( YCPString("label"), YCPString( product->summary() ) );
- ret->add( YCPString("vendor"), YCPString( product->vendor() ) );
- ret->add( YCPString("productname"), YCPString( product->name() ) );
- ret->add( YCPString("productversion"), YCPString( product->edition().version() ) );
- ret->add( YCPString("relnotesurl"), YCPString( product->releaseNotesUrl().asString()));
-
- #warning SourceProductData not finished
- /*
- data->add( YCPString("datadir"), YCPString( descr->content_datadir().asString() ) );
- TODO (?): "baseproductname", "baseproductversion", "defaultbase", "architectures",
- "requires", "linguas", "labelmap", "language", "timezone", "descrdir", "datadir"
- */
-
- break;
- }
- }
-
- if( it == zypp_ptr()->pool().byKindEnd(zypp::ResTraits<zypp::Product>::kind) )
- {
- y2error ("Product for source '%lld' not found", src_id->value());
- }
- }
- catch (...)
- {
- }
-
- return ret;
-}
-
-/****************************************************************************************
- * @builtin SourceProduct
- * @short Obsoleted function, do not use, see SourceProductData builtin
- * @deprecated
- * @param integer
- * @return map empty map
- **/
-YCPValue
-PkgModuleFunctions::SourceProduct (const YCPInteger& id)
-{
- /* TODO FIXME */
- y2error("Pkg::SourceProduct() is obsoleted, use Pkg::SourceProductData() instead!");
- return YCPMap();
-}
-
-
-YCPValue PkgModuleFunctions::SourceProvideFileCommon(const YCPInteger &id,
- const YCPInteger &mid,
- const YCPString& f,
- const YCPBoolean & optional)
-{
- CallInitDownload(std::string(_("Downloading ") + f->value()));
-
- bool found = true;
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- found = false;
-
- extern ZyppRecipients::MediaChangeSensitivity _silent_probing;
- // remember the current value
- ZyppRecipients::MediaChangeSensitivity _silent_probing_old = _silent_probing;
-
- // disable media change callback for optional file
- if (optional->value())
- _silent_probing = ZyppRecipients::MEDIA_CHANGE_OPTIONALFILE;
-
- zypp::filesystem::Pathname path; // FIXME use ManagedMedia
- if (found)
- {
- try
- {
- path = repo->mediaAccess()->provideFile(f->value(), mid->value());
- y2milestone("local path: '%s'", path.asString().c_str());
- }
- catch (const zypp::Exception& excpt)
- {
- found = false;
-
- if (!optional->value())
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2milestone("File not found: %s", f->value_cstr());
- }
- }
- }
-
- // set the original probing value
- _silent_probing = _silent_probing_old;
-
- CallDestDownload();
-
- if (found)
- {
- return YCPString(path.asString());
- }
- else
- {
- return YCPVoid();
- }
-}
-
-
-/****************************************************************************************
- * @builtin SourceProvideFile
- *
- * @short Make a file available at the local filesystem
- * @description
- * Let an InstSrc provide some file (make it available at the local filesystem).
- *
- * @param integer SrcId Specifies the InstSrc .
- * @param integer medianr Number of the media the file is located on ('1' for the 1st media).
- * @param string file Filename relative to the media root.
- *
- * @return string local path as string
- **/
-YCPValue
-PkgModuleFunctions::SourceProvideFile (const YCPInteger& id, const YCPInteger& mid, const YCPString& f)
-{
- return SourceProvideFileCommon(id, mid, f, false /*optional*/);
-}
-
-/****************************************************************************************
- * @builtin SourceProvideOptionalFile
- *
- * @short Make an optional file available at the local filesystem
- * @description
- * Let an InstSrc provide some file (make it available at the local filesystem).
- * If the file doesn't exist don't ask user for another medium and return nil
- *
- * @param integer SrcId Specifies the InstSrc .
- * @param integer medianr Number of the media the file is located on ('1' for the 1st media).
- * @param string file Filename relative to the media root.
- *
- * @return string local path as string
- **/
-YCPValue
-PkgModuleFunctions::SourceProvideOptionalFile (const YCPInteger& id, const YCPInteger& mid, const YCPString& f)
-{
- return SourceProvideFileCommon(id, mid, f, true /*optional*/);
-}
-
-/****************************************************************************************
- * @builtin SourceProvideDir
- * @short make a directory available at the local filesystem
- * @description
- * Let an InstSrc provide some directory (make it available at the local filesystem) and
- * all the files within it (non recursive).
- *
- * @param integer SrcId Specifies the InstSrc .
- * @param integer medianr Number of the media the file is located on ('1' for the 1st media).
- * @param string dir Directoryname relative to the media root.
- * @return string local path as string
- */
-YCPValue
-PkgModuleFunctions::SourceProvideDir (const YCPInteger& id, const YCPInteger& mid, const YCPString& d)
-{
- y2warning("Pkg::SourceProvideDir() is obsoleted use Pkg::SourceProvideDirectory() instead");
- // non optional, non recursive
- return SourceProvideDirectory(id, mid, d, false, false);
-}
-
-
-/****************************************************************************************
- * @builtin SourceProvideDirectory
- * @short make a directory available at the local filesystem
- * @description
- * Download a directory from repository (make it available at the local filesystem) and
- * all the files within it.
- *
- * @param integer id repository to use (id)
- * @param integer mid Number of the media where the directory is located on ('1' for the 1st media).
- * @param string d Directory name relative to the media root.
- * @param boolean optional set to true if the directory may not exist (do not report errors)
- * @param boolean recursive set to true to provide all subdirectories recursively
- * @return string local path as string or nil when an error occured
- */
-YCPValue
-PkgModuleFunctions::SourceProvideDirectory(const YCPInteger& id, const YCPInteger& mid, const YCPString& d, const YCPBoolean &optional, const YCPBoolean &recursive)
-{
- CallInitDownload(std::string(_("Downloading ") + d->value()));
-
- bool found = true;
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- found = false;
-
- zypp::filesystem::Pathname path; // FIXME user ManagedMedia
-
- extern ZyppRecipients::MediaChangeSensitivity _silent_probing;
- // remember the current value
- ZyppRecipients::MediaChangeSensitivity _silent_probing_old = _silent_probing;
-
- // disable media change callback for optional file
- if (optional->value())
- _silent_probing = ZyppRecipients::MEDIA_CHANGE_OPTIONALFILE;
-
- if (found)
- {
- try
- {
- path = repo->mediaAccess()->provideDir(d->value(), recursive->value(), mid->value());
- }
- catch (const zypp::Exception& excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2milestone ("Directory not found: %s", d->value_cstr());
- found = false;
- }
- }
-
- // set the original probing value
- _silent_probing = _silent_probing_old;
-
- CallDestDownload();
-
- if (found)
- {
- return YCPString(path.asString());
- }
- else
- {
- return YCPVoid();
- }
-}
-
-/****************************************************************************************
- * @builtin SourceChangeUrl
- * @short Change Source URL
- * @description
- * Change url of an InstSrc. Used primarely when re-starting during installation
- * and a cd-device changed from hdX to srX since ide-scsi was activated.
- * @param integer SrcId Specifies the InstSrc.
- * @param string url The new url to use.
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceChangeUrl (const YCPInteger& id, const YCPString& u)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- try
- {
- if (repo->repoInfo().baseUrlsSize() > 1)
- {
- // store current urls
- std::set<zypp::Url> baseUrls (repo->repoInfo().baseUrlsBegin(), repo->repoInfo().baseUrlsEnd());
-
- // reset url list and store the new one there
- repo->repoInfo().setBaseUrl(zypp::Url(u->value()));
-
- // add the rest of base urls
- for (std::set<zypp::Url>::const_iterator i = baseUrls.begin();
- i != baseUrls.end(); ++i)
- repo->repoInfo().addBaseUrl(*i);
- }
- else
- repo->repoInfo().setBaseUrl(zypp::Url(u->value()));
- }
- catch (const zypp::Exception & excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error ("Cannot set the new URL for source %s (%lld): %s",
- repo->repoInfo().alias().c_str(), id->asInteger()->value(), excpt.msg().c_str());
- return YCPBoolean(false);
- }
-
- return YCPBoolean(true);
-}
-
-/****************************************************************************************
- * @builtin SourceInstallOrder
- *
- * @short not implemented, do not use (Explicitly set an install order.)
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceInstallOrder (const YCPMap& ord)
-{
- /* TODO FIXME
- YCPList args;
- args->add (ord);
-
- //-------------------------------------------------------------------------------------//
- YcpArgLoad decl(__FUNCTION__);
-
- YCPMap & order_map( decl.arg<YT_MAP, YCPMap>() );
-
- if ( ! decl.load( args ) ) {
- return pkgError_bad_args;
- }
- //-------------------------------------------------------------------------------------//
-
- InstSrcManager::InstOrder order;
- order.reserve( order_map->size() );
- bool error = false;
-
- for ( YCPMapIterator it = order_map->begin(); it != order_map->end(); ++it ) {
-
- if ( it.value()->isInteger() ) {
- InstSrc::UniqueID uId( it.value()->asInteger()->value() );
- InstSrcManager::ISrcId source_id( _y2pm.instSrcManager().getSourceByID( uId ) );
- if ( source_id ) {
- if ( source_id->enabled() ) {
- order.push_back( uId ); // finaly ;)
-
- } else {
- y2error ("order map entry '%s:%s': source not enabled",
- it.key()->toString().c_str(),
- it.value()->toString().c_str() );
- error = true;
- }
- } else {
- y2error ("order map entry '%s:%s': bad source id",
- it.key()->toString().c_str(),
- it.value()->toString().c_str() );
- error = true;
- }
- } else {
- y2error ("order map entry '%s:%s': integer value expected",
- it.key()->toString().c_str(),
- it.value()->toString().c_str() );
- error = true;
- }
- }
- if ( error ) {
- return pkgError( Error::E_bad_args );
- }
-
- // store new instorder
- _y2pm.instSrcManager().setInstOrder( order );
-*/
-
-#warning SourceInstallOrder is not implemented
- return YCPBoolean( true );
-}
-
-
-static std::string timestamp ()
-{
- time_t t = time(NULL);
- struct tm * tmp = localtime(&t);
-
- if (tmp == NULL) {
- return "";
- }
-
- char outstr[50];
- if (strftime(outstr, sizeof(outstr), "%Y%m%d-%H%M%S", tmp) == 0) {
- return "";
- }
- return outstr;
-}
-
-/**
- * Take the ?alias=foo part of old_url, if any, and return it,
- * putting the rest to new_url.
- * \throws Exception on malformed URLs I guess
- */
-static std::string removeAlias (const zypp::Url & old_url,
- zypp::Url & new_url)
-{
- std::string alias;
- new_url = old_url;
- zypp::url::ParamMap query = new_url.getQueryStringMap ();
- zypp::url::ParamMap::iterator alias_it = query.find ("alias");
- if (alias_it != query.end ())
- {
- alias = alias_it->second;
- query.erase (alias_it);
- new_url.setQueryStringMap (query);
- }
- return alias;
-}
-
-std::string PkgModuleFunctions::UniqueAlias(const std::string &alias)
-{
- // make a copy
- std::string ret = alias;
-
- unsigned int id = 0;
- while(aliasExists(ret))
- {
- y2milestone("Alias %s already found: %lld", ret.c_str(), logFindAlias(ret));
-
- // the alias already exists - add a counter
- std::ostringstream ostr;
- ostr << alias << "_" << id;
-
- ret = ostr.str();
-
- y2milestone("Using alias %s", ret.c_str());
- ++id;
- }
-
- return ret;
-}
-
-
-/**
- * helper - add "mountoptions=ro" for mountable URL schemes if "mountoptions" option is not empty and
- * "rw" or "ro" option is missing
- */
-zypp::Url addRO(const zypp::Url &url)
-{
- zypp::Url ret(url);
- std::string scheme = zypp::str::toLower(url.getScheme());
-
- if (scheme == "nfs"
- || scheme == "hd"
- || scheme == "smb"
- || scheme == "iso"
- || scheme == "cd"
- || scheme == "dvd"
- )
- {
- const std::string mountoptions = "mountoptions";
- zypp::media::Mount::Options options(url.getQueryParam(mountoptions));
-
- y2debug("Current mountoptions: %s", options.asString().c_str());
-
- // if mountoptions are empty lizypp uses "ro" by default
- // don't override "rw" option from application
- // don't add "ro" if it's already present
- if (!options.empty() && !options.has("rw") && !options.has("ro"))
- {
- options["ro"];
-
- ret.setQueryParam(mountoptions, options.asString());
- y2milestone("Adding read only mount option: '%s' -> '%s'", url.asString().c_str(), ret.asString().c_str());
- }
- }
-
- return ret;
-}
-
-// helper function
-zypp::Url PkgModuleFunctions::shortenUrl(const zypp::Url &url)
-{
- std::string url_path = url.getPathName();
- std::string begin_path;
- std::string end_path;
-
- // try to convert 'http://server/dir1/dir2/dir3/dir4' -> 'http://server/dir1/.../dir4'
- std::string::size_type pos_first = url_path.find("/");
- if (pos_first == 0)
- {
- pos_first = url_path.find("/", 1);
- }
-
- if (pos_first == std::string::npos)
- {
- const int num = 5;
-
- // "/" not found use the beginning and the end part
- // 'http://server/very_long_directory_name' -> 'http://server/very_..._name'
- begin_path = std::string(url_path, 0, num);
- end_path = std::string(url_path, url_path.size() - num - 1, num);
- }
- else
- {
- unsigned int pos_last = url_path.rfind("/");
- if (pos_last == url_path.size() - 1)
- {
- pos_last = url_path.rfind("/", url_path.size() - 1);
- }
-
- if (pos_last == pos_first || pos_last < pos_first)
- {
- const int num = 5;
-
- // "/" not found use the beginning and the end part
- begin_path = std::string(url_path, 0, num);
- end_path = std::string(url_path, url_path.size() - num - 1, num);
- }
- else
- {
- begin_path = std::string(url_path, 0, pos_first + 1);
- end_path = std::string(url_path, pos_last);
- }
- }
-
- std::string new_path = begin_path + "..." + end_path;
- zypp::Url ret(url);
-
- // use the shorter path
- ret.setPathName(new_path);
- // remove query parameters
- ret.setQueryString("");
- // remove fragmet
- ret.setFragment("");
-
- y2milestone("Using shortened URL: '%s' -> '%s'", url.asString().c_str(), ret.asString().c_str());
- return ret;
-}
-
-/** Create a Source and immediately put it into the SourceManager.
- * \return the SourceId
- * \throws Exception if Source creation fails
-*/
-std::vector<zypp::RepoInfo>::size_type
-PkgModuleFunctions::createManagedSource( const zypp::Url & url_r,
- const zypp::Pathname & path_r,
- const bool base_source,
- const std::string& type,
- const std::string &alias_r )
-{
- // parse URL
- y2milestone ("Original URL: %s, product directory: %s", url_r.asString().c_str(), path_r.asString().c_str());
-
- // #158850#c17, if the URL contains an alias, we use that
- zypp::Url url;
-
- std::string alias = removeAlias(url_r, url);
- y2milestone("Alias from URL: '%s'", alias.c_str());
-
-#warning FIXME: use base_source (base_source vs. addon) (will be probably not needed)
-
- // repository type
- zypp::repo::RepoType repotype;
- zypp::RepoManager repomanager = CreateRepoManager();
-
- if (!type.empty())
- {
- try
- {
- // do conversion from the Yast type ("YaST", "YUM", "Plaindir")
- // to libzypp type ("yast", "yum", "plaindir")
- repotype = repotype.parse(yast2zyppType(type));
- }
- catch (zypp::repo::RepoUnknownTypeException &e)
- {
- y2warning("Unknown source type '%s'", type.c_str());
- }
- }
-
- // the type is not specified or is wrong, autoprobe the type
- if (repotype == zypp::repo::RepoType::NONE)
- {
- zypp::Url probe_url(url_r);
-
- if (!path_r.asString().empty())
- {
- zypp::Pathname pth(probe_url.getPathName());
- pth /= path_r;
-
- probe_url.setPathName(pth.asString());
- }
-
- y2milestone("Probing source type: '%s'", probe_url.asString().c_str());
-
- // autoprobe type of the repository
- repotype = ProbeWithCallbacks(probe_url);
- }
-
- y2milestone("Using source type: %s", repotype.asString().c_str());
-
-
- // create source definition object
- zypp::RepoInfo repo;
-
- std::string name;
-
- // set alias and name
- if (alias.empty())
- {
- // alias not set via URL, use the passed alias or the URL path
- if (alias_r.empty())
- {
- // use the last path element in URL
- std::string url_path = url.getPathName();
-
- std::string::size_type pos_begin = url_path.rfind("/");
- std::string::size_type pos_end = std::string::npos;
-
- // ignore the trailing slash
- if (pos_begin == url_path.size() - 1)
- {
- pos_begin = url_path.rfind("/", url_path.size() - 2);
-
- if (pos_begin != std::string::npos)
- {
- pos_end = url_path.size() - pos_begin - 2;
- }
- }
- else
- {
- pos_end = url_path.size() - pos_begin - 1;
- }
-
- // ignore the found slash character
- pos_begin++;
-
- alias = std::string(url_path, pos_begin, pos_end);
-
- y2milestone("Alias from URL path: %s", alias.c_str());
-
- // fallback
- if (alias.empty())
- {
- y2milestone("URL alias is empty using 'Repository'");
- alias = "Repository";
- }
- }
- else
- {
- alias = alias_r;
- }
-
- name = alias;
- }
- else
- {
- name = alias;
- }
-
-
- y2milestone("Name of the repository: '%s'", name.c_str());
-
- // alias must be unique, add a suffix if it's already used
- alias = UniqueAlias(alias);
-
- // add read only mount option to the URL if needed
- url = addRO(url);
-
- bool autorefresh = true;
-
- std::string scheme = zypp::str::toLower(url.getScheme());
- if (scheme == "cd" || scheme == "dvd")
- {
- y2milestone("Disabling autorefresh for CD/DVD repository");
- autorefresh = false;
- }
-
- repo.setAlias(alias);
- repo.setName(name);
- repo.setType(repotype);
- repo.addBaseUrl(url);
- repo.setPath(path_r);
- repo.setEnabled(true);
- repo.setAutorefresh(autorefresh);
-
- // set metadata path (#293428)
- zypp::Pathname metadatapath = repomanager.metadataPath(repo);
- repo.setMetadataPath(metadatapath);
-
- y2milestone("Adding source '%s' (%s, dir: %s)", repo.alias().c_str(), url.asString().c_str(), path_r.asString().c_str());
- // note: exceptions should be caught by the calling code
- RefreshWithCallbacks(repo);
-
- // build cache if needed
- if (!repomanager.isCached(repo))
- {
- y2milestone("Caching source '%s'...", repo.alias().c_str());
- repomanager.buildCache(repo);
- }
-
- repos.push_back(new YRepo(repo));
-
- y2milestone("Added source '%s': '%s', enabled: %s, autorefresh: %s",
- repo.alias().c_str(),
- repo.baseUrlsBegin()->asString().c_str(),
- repo.enabled() ? "true" : "false",
- repo.autorefresh() ? "true" : "false"
- );
-
- // the source is at the end of the list
- return repos.size() - 1;
-}
-
-/****************************************************************************************
- * @builtin RepositoryAdd
- *
- * @short Register a new repository
- * @description
- * Adds a new repository to the internal structures. The repository is only registered,
- * metadata is not downloaded, use Pkg::SourceRefreshNow() for that. The metadata is also loaded
- * automatically when loading the repository content (Pkg::SourceLoad())
- *
- * @param map map with repository parameters: $[ "enabled" : boolean, "autorefresh" : boolean, "name" : string,
- * "alias" : string, "base_urls" : list<string>, "prod_dir" : string, "type" : string ]
- * @return integer Repository ID or nil on error
- **/
-YCPValue PkgModuleFunctions::RepositoryAdd(const YCPMap ¶ms)
-{
- zypp::RepoInfo repo;
-
- // turn on the repo by default
- repo.setEnabled(true);
- // enable autorefresh by default
- repo.setAutorefresh(true);
-
- if (!params->value( YCPString("enabled") ).isNull() && params->value(YCPString("enabled"))->isBoolean())
- {
- repo.setEnabled(params->value(YCPString("enabled"))->asBoolean()->value());
- }
-
- if (!params->value( YCPString("autorefresh") ).isNull() && params->value(YCPString("autorefresh"))->isBoolean())
- {
- repo.setAutorefresh(params->value(YCPString("autorefresh"))->asBoolean()->value());
- }
-
- std::string alias;
-
- if (!params->value( YCPString("alias") ).isNull() && params->value(YCPString("alias"))->isString())
- {
- alias = params->value(YCPString("alias"))->asString()->value();
- }
-
- if (alias.empty())
- {
- alias = timestamp();
-
- // the alias must be unique
- alias = UniqueAlias(alias);
- }
- else
- {
- if (aliasExists(alias))
- {
- ycperror("alias %s already exists", alias.c_str());
- return YCPVoid();
- }
- }
-
- repo.setAlias(alias);
-
- // use the first base URL as a fallback name
- std::string first_url;
-
- if (!params->value( YCPString("base_urls") ).isNull() && params->value(YCPString("base_urls"))->isList())
- {
- YCPList lst(params->value(YCPString("base_urls"))->asList());
-
- for (int index = 0; index < lst->size(); ++index)
- {
- if( ! lst->value(index)->isString() )
- {
- ycperror( "Pkg::RepositoryAdd(): entry not a string at index %d: %s", index, lst->toString().c_str());
- return YCPVoid();
- }
-
- zypp::Url url;
-
- try
- {
- url = lst->value(index)->asString()->value();
- zypp::Url url_new;
-
- std::string name = removeAlias(url, url_new);
-
- if (!name.empty())
- {
- repo.setName(name);
- url = url_new;
- }
-
- // add read only mount option to the URL if needed
- url = addRO(url);
- }
- catch(const zypp::Exception & expt)
- {
- y2error("Invalid URL: %s", expt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(expt));
- return YCPVoid();
- }
-
- if (index == 0)
- {
- first_url = url.asString();
- }
-
- repo.addBaseUrl(url);
- }
- }
- else
- {
- ycperror("Missing \"base_urls\" key in the map");
- return YCPVoid();
- }
-
- // check name parameter
- if (!params->value( YCPString("name") ).isNull() && params->value(YCPString("name"))->isString())
- {
- repo.setName(params->value(YCPString("name"))->asString()->value());
- }
- else
- {
- // if the key "name" is missing and the name hasn't been set by ?alias= in the URL
- // then use the first URL as the name
- if (repo.name().empty())
- {
- repo.setName(first_url);
- }
- }
-
- if (!params->value( YCPString("type") ).isNull() && params->value(YCPString("type"))->isString())
- {
- std::string type = yast2zyppType(params->value(YCPString("type"))->asString()->value());
-
- try
- {
- zypp::repo::RepoType repotype(type);
- repo.setType(repotype);
- }
- catch (zypp::repo::RepoUnknownTypeException &e)
- {
- ycperror("Unknown source type '%s': %s", type.c_str(), e.asString().c_str());
- _last_error.setLastError(ExceptionAsString(e));
- return YCPVoid();
- }
-
- }
-
- if (!params->value( YCPString("prod_dir") ).isNull() && params->value(YCPString("prod_dir"))->isString())
- {
- repo.setPath(params->value(YCPString("prod_dir"))->asString()->value());
- }
-
- // set metadata path (#293428)
- zypp::RepoManager repomanager = CreateRepoManager();
- zypp::Pathname metadatapath = repomanager.metadataPath(repo);
- repo.setMetadataPath(metadatapath);
-
- repos.push_back(new YRepo(repo));
-
- // the new source is at the end of the list
- return YCPInteger(repos.size() - 1);
-}
-
-/****************************************************************************************
- * @builtin SourceCacheCopyTo
- *
- * @short Copy cache data of all installation sources to the target
- * @description
- * Copy cache data of all installation sources to the target located below 'dir'.
- * To be called at end of initial installation.
- *
- * @param string dir Root directory of target.
- * @return boolean true on success
- **/
-YCPValue
-PkgModuleFunctions::SourceCacheCopyTo (const YCPString& dir)
-{
- // error message (followed by detailed description)
- const std::string msg = _("Error: Cannot copy the cache to the target directory\n");
-
- std::string d = dir->value();
- y2milestone("Copying source cache to '%s'...", d.c_str());
-
- if (d.empty())
- {
- y2error("Empty parameter in Pkg::SourceCacheCopyTo()!");
- return YCPBoolean(false);
- }
-
- std::string target = d + "/var/cache";
-
- // create the target dir
- const char* argv[] =
- {
- "mkdir",
- // create parent dir
- "-p",
- // finish parameter list
- "--",
- // target
- target.c_str(),
- NULL
- };
-
- // discard stderr, no pty, stderr_fd = -1, use the default locale
- zypp::ExternalProgram prog(argv, zypp::ExternalProgram::Discard_Stderr, false, -1, true);
-
- int code = prog.close();
-
- if (code)
- {
- // error message (followed by directory name)
- _last_error.setLastError(msg + _("Cannot create directory ") + target);
- y2error("Cannot create target directory %s", target.c_str());
- return YCPBoolean(false);
- }
-
- // copy /var/cache/zypp to the target system
- const char* argv2[] =
- {
- "cp",
- // preserve time stamps
- "-a",
- // recursive
- "-r",
- // finish parameter list
- "--",
- // source
- "/var/cache/zypp",
- // target
- target.c_str(),
- NULL
- };
-
- // discard stderr, no pty, stderr_fd = -1, use the default locale
- zypp::ExternalProgram prog2(argv2, zypp::ExternalProgram::Discard_Stderr, false, -1, true);
-
- int code2 = prog2.close();
-
- if (code2)
- {
- // error message
- _last_error.setLastError(msg + _("Copying failed"));
- y2error("Cannot copy /var/cache/zypp to %s", d.c_str());
- }
-
- return YCPBoolean(!code2);
-}
-
-/****************************************************************************************
- * @builtin SourceScan
- * @short Scan a Source Media
- * @description
- * Load all InstSrces found at media_url, i.e. all sources mentioned in /media.1/products.
- * If no /media.1/products is available, InstSrc is expected to be located directly
- * below media_url (product_dir: /).
- *
- * If a product_dir is provided, only the InstSrc located at media_url/product_dir is loaded.
- *
- * In contrary to @ref SourceCreate, InstSrces are loaded into the InstSrcManager,
- * but not enabled (packages and selections are not provided to the PackageManager),
- * and the SrcIds of <b>all</b> InstSrces found are returned.
- *
- * @param string url The media to scan.
- * @optarg string product_dir Restrict scan to a certain InstSrc located in media_url/product_dir.
- *
- * @return list<integer> list of SrcIds (integer).
- **/
-YCPValue
-PkgModuleFunctions::SourceScan (const YCPString& media, const YCPString& pd)
-{
- zypp::Url url;
-
- try {
- url = zypp::Url(media->value ());
- }
- catch(const zypp::Exception & expt )
- {
- y2error ("Invalid URL: %s", expt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(expt));
- return YCPList();
- }
-
- zypp::Pathname pn(pd->value ());
-
- YCPList ids;
- std::vector<zypp::RepoInfo>::size_type id;
-
- if ( pd->value().empty() ) {
-
- // scan all sources
- zypp::MediaProductSet products;
-
- try
- {
- y2milestone("Scanning products in %s ...", url.asString().c_str());
- ScanProductsWithCallBacks(url);
- products = available_products;
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("Scanning products for '%s' has failed"
- , url.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- return ids;
- }
-
- if( products.empty() )
- {
- // no products found, use the base URL instead
- zypp::MediaProductEntry entry;
- products.insert(entry);
- }
-
- for( zypp::MediaProductSet::const_iterator it = products.begin();
- it != products.end() ; ++it )
- {
- try
- {
- y2milestone("Using product %s in directory %s", it->_name.c_str(), it->_dir.c_str());
- id = createManagedSource(url, it->_dir, false, "", it->_name);
- ids->add( YCPInteger(id) );
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("SourceScan for '%s' product '%s' has failed"
- , url.asString().c_str(), pn.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- }
- }
- } else {
- y2debug("Creating source...");
-
- try
- {
- id = createManagedSource(url, pn, false, "", "");
- ids->add( YCPInteger(id) );
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("SourceScan for '%s' product '%s' has failed"
- , url.asString().c_str(), pn.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- }
- }
-
- y2milestone("Found sources: %s", ids->toString().c_str() );
-
- return ids;
-}
-
-/****************************************************************************************
- * @builtin SourceCreate
- *
- * @short Create a Source
- * @description
- * Load and enable all InstSrces found at media_url, i.e. all sources mentioned in /media.1/products.
- * If no /media.1/products is available, InstSrc is expected to be located directly below
- * media_url (product_dir: /).
+/* ------------------------------------------------------------------------------
+ * Copyright (c) 2007 Novell, Inc. All Rights Reserved.
*
- * If a product_dir is provided, only the InstSrc located at media_url/product_dir is loaded
- * and enabled.
*
- * @param string url The media to scan.
- * @optarg string product_dir Restrict scan to a certain InstSrc located in media_url/product_dir.
+ * This program is free software; you can redistribute it and/or modify it under
+ * the terms of version 2 of the GNU General Public License as published by the
+ * Free Software Foundation.
*
- * @return integer The source_id of the first InstSrc found on the media.
- **/
-YCPValue
-PkgModuleFunctions::SourceCreate (const YCPString& media, const YCPString& pd)
-{
- // not base product, autoprobe source type
- return SourceCreateEx (media, pd, false, YCPString(""));
-}
-
-YCPValue
-PkgModuleFunctions::SourceCreateBase (const YCPString& media, const YCPString& pd)
-{
- // base product, autoprobe source type
- return SourceCreateEx (media, pd, true, YCPString(""));
-}
-
-/**
- * @builtin SourceCreateType
- * @short Create source of required type
- * @description
- * Create a source without autoprobing the source type. This builtin should be used only for "Plaindir" sources, because Plaindir sources are not automatically probed in SourceCreate() builtin.
- * @param media URL of the source
- * @param pd product directory (if empty the products will be searched)
- * @param type type of the source ("YaST", "YUM" or "Plaindir")
-*/
-
-YCPValue
-PkgModuleFunctions::SourceCreateType (const YCPString& media, const YCPString& pd, const YCPString& type)
-{
- // not base product, autoprobe source type
- return SourceCreateEx (media, pd, false, type);
-}
-
-YCPValue
-PkgModuleFunctions::SourceCreateEx (const YCPString& media, const YCPString& pd, bool base, const YCPString& source_type)
-{
- y2debug("Creating source...");
-
- zypp::Pathname pn(pd->value ());
-
- zypp::Url url;
-
- try {
- url = zypp::Url(media->value ());
- }
- catch(const zypp::Exception & expt )
- {
- y2error ("Invalid URL: %s", expt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(expt));
- return YCPInteger (-1LL);
- }
-
-
- YCPList ids;
- std::vector<zypp::RepoInfo>::size_type ret = -1;
-
- const std::string type = source_type->value();
-
- if ( pd->value().empty() ) {
- // scan all sources
- zypp::MediaProductSet products;
-
- try {
- ScanProductsWithCallBacks(url);
- products = available_products;
- }
- catch ( const zypp::Exception& excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error( "Cannot read the product list from the media" );
- return YCPInteger(-1LL);
- }
-
- if( products.empty() )
- {
- // no products found, use the base URL instead
- zypp::MediaProductEntry entry ;
- products.insert( entry );
- }
-
- for( zypp::MediaProductSet::const_iterator it = products.begin();
- it != products.end() ; ++it )
- {
- try
- {
- std::vector<zypp::RepoInfo>::size_type id = createManagedSource(url, it->_dir, base, type, it->_name);
- YRepo_Ptr repo = logFindRepository(id);
-
- LoadResolvablesFrom(repo->repoInfo());
-
- // return the id of the first product
- if ( it == products.begin() )
- ret = id;
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("SourceCreate for '%s' product '%s' has failed"
- , url.asString().c_str(), pn.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- return YCPInteger(-1LL);
- }
- }
- } else {
- y2debug("Creating source...");
-
- try
- {
- ret = createManagedSource(url, pn, base, type, "");
-
- YRepo_Ptr repo = logFindRepository(ret);
- repo->repoInfo().setEnabled(true);
-
- LoadResolvablesFrom(repo->repoInfo());
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("SourceCreate for '%s' product '%s' has failed"
- , url.asString().c_str(), pn.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- }
- }
-
- PkgFreshen();
- return YCPInteger(repos.size() - 1);
-}
-
-
-/****************************************************************************************
- * @builtin SourceSetEnabled
- *
- * @short Set the default activation state of an InsrSrc.
- * @param integer SrcId Specifies the InstSrc.
- * @param boolean enabled Default activation state of source.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceSetEnabled (const YCPInteger& id, const YCPBoolean& e)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- // no change required
- bool enable = e->value();
- if ((enable && repo->repoInfo().enabled())
- || (!enable && !repo->repoInfo().enabled()))
- return YCPBoolean(true);
-
- bool success = true;
-
- try
- {
- repo->repoInfo().setEnabled(enable);
-
- // add/remove resolvables
- if (enable)
- {
- // load resolvables only when they are missing
- if (!AnyResolvableFrom(repo->repoInfo().alias()))
- {
- success = LoadResolvablesFrom(repo->repoInfo());
- }
- }
- else
- {
- // the source has been disabled, remove resolvables from the pool
- RemoveResolvablesFrom(repo->repoInfo().alias());
- }
-
- PkgFreshen();
- }
- catch (const zypp::Exception& excpt)
- {
- std::string alias = repo->repoInfo().alias();
- y2error ("Error for '%s': %s", alias.c_str(), excpt.asString().c_str());
- _last_error.setLastError(alias + ": " + ExceptionAsString(excpt));
- success = false;
- }
-
- return YCPBoolean(success);
-}
-
-/****************************************************************************************
- * @builtin SourceSetAutorefresh
- *
- * @short Set whether this source should automaticaly refresh it's
- * meta data when it gets enabled. (default true, if not CD/DVD)
- * @param integer SrcId Specifies the InstSrc.
- * @param boolean enabled Whether autorefresh should be turned on or off.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceSetAutorefresh (const YCPInteger& id, const YCPBoolean& e)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- repo->repoInfo().setAutorefresh(e->value());
-
- return YCPBoolean( true );
-}
-
-/****************************************************************************************
- * @builtin SourceFinish
- * @short Disable an Installation Source
- * @param integer SrcId Specifies the InstSrc.
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceFinish (const YCPInteger& id)
-{
- return SourceSetEnabled(id, false);
-}
-
-/****************************************************************************************
- * @builtin SourceRefreshNow
- * @short Attempt to immediately refresh a Source
- * @description
- * The InsrSrc will be encouraged to check and refresh all metadata
- * cached on disk.
- *
- * @param integer SrcId Specifies the InstSrc.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceRefreshNow (const YCPInteger& id)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- try
- {
- zypp::RepoManager repomanager = CreateRepoManager();
- y2milestone("Refreshing metadata '%s'", repo->repoInfo().alias().c_str());
- RefreshWithCallbacks(repo->repoInfo());
-
- y2milestone("Caching source '%s'...", repo->repoInfo().alias().c_str());
- repomanager.buildCache(repo->repoInfo());
- }
- catch ( const zypp::Exception & expt )
- {
- y2error ("Error while refreshing the source: %s", expt.asString().c_str());
- _last_error.setLastError(repo->repoInfo().alias() + ": " + ExceptionAsString(expt));
- return YCPBoolean(false);
- }
-
- return YCPBoolean( true );
-}
-
-/****************************************************************************************
- * @builtin SourceDelete
- * @short Delete a Source
- * @description
- * Delete an InsrSrc. The InsrSrc together with all metadata cached on disk
- * is removed. The SrcId passed becomes invalid (other SrcIds stay valid).
- *
- * @param integer SrcId Specifies the InstSrc.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceDelete (const YCPInteger& id)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- bool success = true;
-
- try
- {
- // the resolvables cannot be used anymore, remove them
- RemoveResolvablesFrom(repo->repoInfo().alias());
-
- // update 'repos'
- repo->setDeleted();
-
- PkgFreshen();
- }
- catch (const zypp::Exception& excpt)
- {
- std::string alias = repo->repoInfo().alias();
- y2error ("Error for '%s': %s", alias.c_str(), excpt.asString().c_str());
- _last_error.setLastError(alias + ": " + ExceptionAsString(excpt));
- success = false;
- }
-
- return YCPBoolean(success);
-}
-
-/****************************************************************************************
- * @builtin SourceEditGet
- *
- * @short Get state of Sources
- * @description
- * Return a list of states for all known InstSources sorted according to the
- * source priority (highest first). A source state is a map:
- * $[
- * "SrcId" : YCPInteger,
- * "enabled" : YCPBoolean
- * "autorefresh": YCPBoolean
- * ];
- *
- * @return list<map> list of source states (map)
- **/
-YCPValue
-PkgModuleFunctions::SourceEditGet ()
-{
- YCPList ret;
-
- unsigned long index = 0;
- for( std::vector<YRepo_Ptr>::const_iterator it = repos.begin(); it != repos.end(); ++it, ++index)
- {
- if (!(*it)->isDeleted())
- {
- YCPMap src_map;
-
- src_map->add(YCPString("SrcId"), YCPInteger(index));
- // Note: enabled() is tribool
- src_map->add(YCPString("enabled"), YCPBoolean((*it)->repoInfo().enabled()));
- // Note: autorefresh() is tribool
- src_map->add(YCPString("autorefresh"), YCPBoolean((*it)->repoInfo().autorefresh()));
- src_map->add(YCPString("name"), YCPString((*it)->repoInfo().name()));
-
- ret->add(src_map);
- }
- }
-
- return ret;
-}
-
-/****************************************************************************************
- * @builtin SourceEditSet
- *
- * @short Configure properties of installation sources
- * @description
- * Set states of installation sources. Note: Enabling/disabling a source does not
- * (un)load the packages from the source! Use SourceSetEnabled() if you need to refresh
- * the packages in the pool.
- *
- * @param list source_states List of source states. Same format as returned by
- * @see SourceEditGet.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceEditSet (const YCPList& states)
-{
- bool error = false;
-
- for (int index = 0; index < states->size(); index++ )
- {
- if( ! states->value(index)->isMap() )
- {
- ycperror( "Pkg::SourceEditSet, entry not a map at index %d", index);
- error = true;
- continue;
- }
-
- YCPMap descr = states->value(index)->asMap();
-
- if (descr->value( YCPString("SrcId") ).isNull() || !descr->value(YCPString("SrcId"))->isInteger())
- {
- ycperror( "Pkg::SourceEditSet, SrcId not defined for a source description at index %d", index);
- error = true;
- continue;
- }
-
- std::vector<YRepo_Ptr>::size_type id = descr->value( YCPString("SrcId") )->asInteger()->value();
-
- YRepo_Ptr repo = logFindRepository(id);
- if (!repo)
- {
- ycperror( "Pkg::SourceEditSet, source %d not found", index);
- error = true;
- continue;
- }
-
- // now, we have the source
- if( ! descr->value( YCPString("enabled")).isNull() && descr->value(YCPString("enabled"))->isBoolean ())
- {
- bool enable = descr->value(YCPString("enabled"))->asBoolean ()->value();
-
- if (repo->repoInfo().enabled() != enable)
- {
- ycpwarning("Pkg::SourceEditSet() does not refresh the pool (src: %zd, state: %s)", id, enable ? "disabled -> enabled" : "enabled -> disabled");
- }
-
- y2debug("set enabled: %d", enable);
- repo->repoInfo().setEnabled(enable);
- }
-
- if( !descr->value(YCPString("autorefresh")).isNull() && descr->value(YCPString("autorefresh"))->isBoolean ())
- {
- bool autorefresh = descr->value(YCPString("autorefresh"))->asBoolean()->value();
- y2debug("set autorefresh: %d", autorefresh);
- repo->repoInfo().setAutorefresh( autorefresh );
- }
-
- if( !descr->value(YCPString("name")).isNull() && descr->value(YCPString("name"))->isString())
- {
- // rename the source
- y2debug("set name: %s", descr->value(YCPString("name"))->asString()->value().c_str());
- repo->repoInfo().setName(descr->value(YCPString("name"))->asString()->value());
- }
-
-#warning SourceEditSet ordering not implemented yet
- }
-
- PkgFreshen();
- return YCPBoolean( !error );
-}
-
-/////////////////////////////////////////////////////////////////////////////////////////
-//
-// DEPRECATED
-//
-/////////////////////////////////////////////////////////////////////////////////////////
-
-/****************************************************************************************
- * Pkg::SourceRaisePriority (integer SrcId) -> bool
- *
- * Raise priority of source.
- *
- * @param SrcId Specifies the InstSrc.
- *
- * @return bool
- **/
-YCPValue
-PkgModuleFunctions::SourceRaisePriority (const YCPInteger& id)
-{
-#warning SourceRaisePriority is not implemented
- y2warning("SourceRaisePriority is NOT implemented");
-/* zypp::Source_Ref src;
-
- try {
- src = logFindRepository(id->value());
- }
- catch (const zypp::Exception& excpt)
- {
- return YCPBoolean(false);
- }
-
- // raise priority by one
- src.setPriority(src.priority() + 1);
-*/
-
- return YCPBoolean( true );
-
-}
-
-/****************************************************************************************
- * Pkg::SourceLowerPriority (integer SrcId) -> void
- *
- * Lower priority of source.
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+ * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
- * @param SrcId Specifies the InstSrc.
+ * You should have received a copy of the GNU General Public License along with
+ * this program; if not, contact Novell, Inc.
*
- * @return bool
+ * To contact Novell about this file by physical or electronic mail, you may find
+ * current contact information at www.novell.com.
+ * ------------------------------------------------------------------------------
*/
-YCPValue
-PkgModuleFunctions::SourceLowerPriority (const YCPInteger& id)
-{
-#warning SourceLowerPriority is not implemented
- y2warning("SourceLowerPriority is NOT implemented");
-/*
- zypp::Source_Ref src;
-
- try {
- src = logFindRepository(id->value());
- }
- catch (const zypp::Exception& excpt)
- {
- return YCPBoolean(false);
- }
- // lower priority by one
- src.setPriority(src.priority() - 1);
+/*
+ File: $Id:$
+ Author: Ladislav Slezák <lslezak(a)novell.com>
+ Summary: Functions for adding/removing resolvables in the pool
*/
- return YCPBoolean( true );
-}
-
-/****************************************************************************************
- * Pkg::SourceSaveRanks () -> boolean
- *
- * @short Obsoleted function, do not use
- * @return boolean true
- **/
-YCPValue
-PkgModuleFunctions::SourceSaveRanks ()
-{
- y2error( "SourceSaveRanks not implemented" );
-
- return YCPBoolean( true );
-}
-
-/****************************************************************************************
- * @builtin SourceMoveDownloadArea
- *
- * @short Move download area of CURL-based sources to specified directory
- * @param path specifies the path to move the download area to
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceMoveDownloadArea (const YCPString & path)
-{
- try
- {
- y2milestone("Moving download area of all sources to %s", path->value().c_str());
- zypp::media::MediaManager manager;
- manager.setAttachPrefix(path->value());
- }
- catch (zypp::Exception & excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error("Pkg::SourceMoveDownloadArea has failed: %s", excpt.msg().c_str());
- return YCPBoolean(false);
- }
- y2milestone( "Download areas moved");
+#include <Callbacks.h>
+#include <Callbacks.YCP.h>
- return YCPBoolean(true);
-}
+#include <PkgModule.h>
+#include <PkgModuleFunctions.h>
/*
* A helper function - remove all resolvables from the repository from the pool
@@ -2796,145 +132,3 @@
y2milestone("Pool size at end: %d (loaded %d resolvables)", size_end, size_end - size_start);
return success;
}
-
-/****************************************************************************************
- * @builtin RepositoryProbe
- *
- * @short Probe type of the repository
- * @param url specifies the path to the repository
- * @param prod_dir product directory (if empty the url is probed directly)
- * @return string repository type ("NONE" if type could be determined, nil if an error occurred (e.g. resolving the hostname)
- **/
-YCPValue PkgModuleFunctions::RepositoryProbe(const YCPString& url, const YCPString& prod_dir)
-{
- y2milestone("Probing repository type: '%s'...", url->value().c_str());
- zypp::RepoManager repomanager = CreateRepoManager();
- std::string ret;
-
- try
- {
- zypp::Url probe_url(url->value());
-
- // add the product directory
- std::string prod = prod_dir->value();
-
- if (!prod.empty())
- {
- // add "/" at the begining if it's missing
- if (std::string(prod, 0, 1) != "/")
- {
- prod = "/" + prod;
- }
-
- // merge the URL path and the product path
- std::string path = probe_url.getPathName();
- path += prod;
-
- y2milestone("Using probing path: %s", path.c_str());
- probe_url.setPathName(path);
- }
-
- // add "ro" mount option
- probe_url = addRO(probe_url);
-
- // autoprobe type of the repository
- zypp::repo::RepoType repotype = ProbeWithCallbacks(probe_url);
-
- ret = zypp2yastType(repotype.asString());
- y2milestone("Detected type: '%s'...", ret.c_str());
- }
- catch (const zypp::Exception& excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error( "Cannot detect the repository type" );
- return YCPVoid();
- }
-
- return YCPString(ret);
-}
-
-/****************************************************************************************
- * @builtin RepositoryScan
- *
- * @short Scan available products in the repository
- * @param url specifies the path to the repository
- * @return list<list<string>> list of the products: [ [ <product_name_1> <directory_1> ], ...]
- **/
-YCPValue PkgModuleFunctions::RepositoryScan(const YCPString& url)
-{
- zypp::MediaProductSet products;
-
- try
- {
- zypp::Url baseurl(url->value());
-
- baseurl = addRO(baseurl);
-
- ScanProductsWithCallBacks(baseurl);
- products = available_products;
- }
- catch ( const zypp::Exception& excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error( "Cannot read the product list from the media" );
- return YCPList();
- }
-
- YCPList ret;
-
- for( zypp::MediaProductSet::const_iterator it = products.begin();
- it != products.end() ; ++it )
- {
- YCPList prod;
-
- // add product directory
- prod.add(YCPString(it->_name));
- // add product name
- prod.add(YCPString(it->_dir.asString()));
-
- ret.add(prod);
- }
-
- y2milestone("Found products: %s", ret->toString().c_str());
-
- return ret;
-}
-
-// convert libzypp type to yast strings ("YaST", "YUM" or "Plaindir")
-std::string PkgModuleFunctions::zypp2yastType(const std::string &type)
-{
- std::string ret(type);
-
- if (type_conversion_table.empty())
- {
- // initialize the conversion map
- type_conversion_table["rpm-md"] = "YUM";
- type_conversion_table["yast2"] = "YaST";
- type_conversion_table["plaindir"] = "Plaindir";
- type_conversion_table["NONE"] = "NONE";
- }
-
- std::map<std::string,std::string>::const_iterator it = type_conversion_table.find(type);
-
- // found in the conversion table
- if (it != type_conversion_table.end())
- {
- ret = it->second;
- }
- else
- {
- y2error("Cannot convert type '%s'", type.c_str());
- }
-
- return ret;
-}
-
-std::string PkgModuleFunctions::yast2zyppType(const std::string &type)
-{
- // do conversion from the Yast type ("YaST", "YUM", "Plaindir")
- // to libzypp type ("yast", "yum", "plaindir")
- // we can simply use toLower instead of a conversion table
- // in this case
- return zypp::str::toLower(type);
-}
-
Copied: trunk/pkg-bindings/src/Source_Save.cc (from r42708, trunk/pkg-bindings/src/Source.cc)
URL: http://svn.opensuse.org/viewcvs/yast/trunk/pkg-bindings/src/Source_Save.cc?…
==============================================================================
--- trunk/pkg-bindings/src/Source.cc (original)
+++ trunk/pkg-bindings/src/Source_Save.cc Thu Dec 6 07:56:58 2007
@@ -1,2940 +1,223 @@
-/*---------------------------------------------------------------------\
-| |
-| __ __ ____ _____ ____ |
-| \ \ / /_ _/ ___|_ _|___ \ |
-| \ V / _` \___ \ | | __) | |
-| | | (_| |___) || | / __/ |
-| |_|\__,_|____/ |_| |_____| |
-| |
-| core system |
-| (C) SuSE GmbH |
-\----------------------------------------------------------------------/
-
- File: PkgModuleFunctionsSource.cc
-
- Author: Klaus Kaempf <kkaempf(a)suse.de>
- Maintainer: Klaus Kaempf <kkaempf(a)suse.de>
-
- Summary: Access to Installation Sources
- Namespace: Pkg
- Purpose: Access to InstSrc
- Handles source related Pkg::function (list_of_arguments) calls
- from WFMInterpreter.
-/-*/
-//#include <unistd.h>
-//#include <sys/statvfs.h>
-
-#include <iostream>
-
-#include <ycpTools.h>
-#include <PkgModule.h>
-#include <PkgModuleFunctions.h>
-
-#include <Callbacks.h>
-#include <Callbacks.YCP.h>
-
-#include <zypp/Product.h>
-#include <zypp/media/MediaManager.h>
-#include <zypp/media/Mount.h>
-#include <zypp/Pathname.h>
-
-#include <zypp/RepoInfo.h>
-#include <zypp/RepoManager.h>
-#include <zypp/Fetcher.h>
-#include <zypp/repo/RepoType.h>
-#include <zypp/MediaProducts.h>
-#include <zypp/ExternalProgram.h>
-#include <zypp/ProgressData.h>
-
-#include <sstream> // ostringstream
-
-#include <PkgProgress.h>
-
-/*
- Textdomain "pkg-bindings"
-*/
-
-// scanned available products
-// hack: zypp/MediaProducts.h cannot be included in PkgModuleFunctions.h
-zypp::MediaProductSet available_products;
-
-// this method should be used instead of zypp::productsInMedia()
-// it initializes the download callbacks
-void PkgModuleFunctions::ScanProductsWithCallBacks(const zypp::Url &url)
-{
- CallInitDownload(std::string(_("Scanning products in ") + url.asString()));
-
- extern ZyppRecipients::MediaChangeSensitivity _silent_probing;
- // remember the current value
- ZyppRecipients::MediaChangeSensitivity _silent_probing_old = _silent_probing;
-
- // disable media change callback for optional file
- _silent_probing = ZyppRecipients::MEDIA_CHANGE_DISABLE;
-
- y2milestone("Scanning products in %s ...", url.asString().c_str());
-
- try
- {
- available_products.clear();
- zypp::productsInMedia(url, available_products);
- }
- catch(...)
- {
- // call the final event even in case of exception
- CallDestDownload();
-
- // restore the probing flag
- _silent_probing = _silent_probing_old;
-
- // rethrow the execption
- throw;
- }
-
- CallDestDownload();
-
- // restore the probing flag
- _silent_probing = _silent_probing_old;
-}
-
-void PkgModuleFunctions::CallSourceReportStart(const std::string &text)
-{
- // get the YCP callback handler
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_SourceReportStart);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- // add parameters
- ycp_handler->appendParameter( YCPInteger(0LL) );
- ycp_handler->appendParameter( YCPString("") );
- ycp_handler->appendParameter( YCPString(text) );
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-
-void PkgModuleFunctions::CallSourceReportEnd(const std::string &text)
-{
- // get the YCP callback handler for end event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_SourceReportEnd);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- // add parameters
- ycp_handler->appendParameter( YCPInteger(0LL) );
- ycp_handler->appendParameter( YCPString("") );
- ycp_handler->appendParameter( YCPString(text) );
- ycp_handler->appendParameter( YCPString("NO_ERROR") );
- ycp_handler->appendParameter( YCPString("") );
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-
-void PkgModuleFunctions::CallSourceReportInit()
-{
- // get the YCP callback handler for init event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_SourceReportInit);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-
-void PkgModuleFunctions::CallSourceReportDestroy()
-{
- // get the YCP callback handler for destroy event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_SourceReportDestroy);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-
-void PkgModuleFunctions::CallInitDownload(const std::string &task)
-{
- // get the YCP callback handler for destroy event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_InitDownload);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- ycp_handler->appendParameter(YCPString(task));
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-
-void PkgModuleFunctions::CallDestDownload()
-{
- // get the YCP callback handler for destroy event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_DestDownload);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-
-// this method should be used instead of RepoManager::refreshMetadata()
-void PkgModuleFunctions::RefreshWithCallbacks(const zypp::RepoInfo &repo)
-{
- CallInitDownload(std::string(_("Refreshing repository ") + repo.alias()));
-
- try
- {
- zypp::RepoManager repomanager = CreateRepoManager();
- repomanager.refreshMetadata(repo);
- }
- catch(...)
- {
- // call the final event even in case of exception
- CallDestDownload();
- // rethrow the execption
- throw;
- }
-
- CallDestDownload();
-}
-
-// this method should be used instead of RepoManager::probe()
-zypp::repo::RepoType PkgModuleFunctions::ProbeWithCallbacks(const zypp::Url &url)
-{
- CallInitDownload(std::string(_("Probing repository ") + url.asString()));
-
- zypp::repo::RepoType repotype;
-
- extern ZyppRecipients::MediaChangeSensitivity _silent_probing;
- // remember the current value
- ZyppRecipients::MediaChangeSensitivity _silent_probing_old = _silent_probing;
-
- // disable media change callback for optional file
- _silent_probing = ZyppRecipients::MEDIA_CHANGE_DISABLE;
-
- try
- {
- // probe type of the repository
- zypp::RepoManager repomanager = CreateRepoManager();
- repotype = repomanager.probe(url);
- }
- catch(...)
- {
- // call the final event even in case of exception
- CallDestDownload();
-
- // restore the probing flag
- _silent_probing = _silent_probing_old;
-
- // rethrow the execption
- throw;
- }
-
- CallDestDownload();
-
- // restore the probing flag
- _silent_probing = _silent_probing_old;
-
- return repotype;
-}
-
-/**
- * Logging helper:
- * call zypp::SourceManager::sourceManager()->findSource
- * and in case of exception, log error and setLastError AND RETHROW
- */
-YRepo_Ptr PkgModuleFunctions::logFindRepository(std::vector<YRepo_Ptr>::size_type id)
-{
- try
- {
- if (id < 0 || id >= repos.size())
- {
- // not found
- throw(std::exception());
- }
-
- if (!repos[id])
- {
- // not found
- throw(std::exception());
- }
-
- if (repos[id]->isDeleted())
- {
- y2error("Source %zd has been deleted, the ID is not valid", id);
- return YRepo_Ptr();
- }
-
- return repos[id];
- }
- catch (...)
- {
- y2error("Cannot find source with ID: %zd", id);
- // TODO: improve the error message
- _last_error.setLastError(_("Cannot find source"));
- }
-
- // not found, return empty pointer
- return YRepo_Ptr();
-}
-
-long long PkgModuleFunctions::logFindAlias(const std::string &alias) const
-{
- std::vector<YRepo_Ptr>::size_type index = 0;
-
- for(std::vector<YRepo_Ptr>::const_iterator it = repos.begin(); it != repos.end() ; ++it, ++index)
- {
- if (!(*it)->isDeleted() && (*it)->repoInfo().alias() == alias)
- return index;
- }
-
- return -1LL;
-}
-
-bool PkgModuleFunctions::aliasExists(const std::string &alias) const
-{
- for(std::vector<YRepo_Ptr>::const_iterator it = repos.begin(); it != repos.end() ; ++it)
- {
- if (!(*it)->isDeleted() && (*it)->repoInfo().alias() == alias)
- return true;
- }
-
- return false;
-}
-
-/****************************************************************************************
- * @builtin SourceSetRamCache
- * @short Obsoleted function, do not use
- * @param boolean
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceSetRamCache (const YCPBoolean& a)
-{
- y2warning( "Pkg::SourceSetRamCache is obsolete and does nothing");
- return YCPBoolean( true );
-}
-
-
-/****************************************************************************************
- * @builtin SourceRestore
- *
- * @short Restore the sources from the persistent store
- * @description
- * Make sure the Source Manager is up and knows all available installation sources.
- * It's safe to call this multiple times, and once the installation sources are
- * actually enabled, it's even cheap
- *
- * @return boolean True on success
- **/
-YCPValue
-PkgModuleFunctions::SourceRestore()
-{
- if (repos.size() > 0)
- {
- y2warning("Number of registered repositories: %zd, skipping repository load!", repos.size());
- return YCPBoolean(true);
- }
-
- bool success = true;
-
- try
- {
- zypp::RepoManager repomanager = CreateRepoManager();
- std::list<zypp::RepoInfo> reps = repomanager.knownRepositories();
-
- repos.clear();
- for (std::list<zypp::RepoInfo>::iterator it = reps.begin();
- it != reps.end(); ++it)
- {
- repos.push_back(new YRepo(*it));
- }
- }
- catch (const zypp::Exception& excpt)
- {
- // FIXME: assuming the sources are already initialized
- y2error ("Error in SourceRestore: %s", excpt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- success = false;
- }
-
- return YCPBoolean(success);
-}
-
-/****************************************************************************************
- * @builtin SourceGetBrokenSources
- *
- * @short Return list of broken sources (sources which failed to restore)
- * @description
- * Get list of all sources which could not have been restored.
- * @return list<string> list of aliases (product names or URLs)
- **/
-YCPValue PkgModuleFunctions::SourceGetBrokenSources()
-{
- y2warning("Pkg::SourceGetBrokenSources() is obsoleted, it's not needed anymore.");
- return YCPList();
-}
-
-bool PkgModuleFunctions::SourceLoadReceiver(const zypp::ProgressData &progress)
-{
- y2milestone("Source Load receiver: %lld (%lld%%)", progress.val(), progress.reportValue());
-
- // get the YCP callback handler for destroy event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_ProcessProgress);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- ycp_handler->appendParameter(YCPInteger(progress.reportValue()));
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-
- return true;
-}
-
-/****************************************************************************************
- * @builtin SourceLoad
- *
- * @short Load resolvables from the installation sources
- * @description
- * Refresh the pool - Add/remove resolvables from the enabled/disabled sources.
- * @return boolean True on success
- **/
-YCPValue
-PkgModuleFunctions::SourceLoad()
-{
- std::list<std::string> stages;
- stages.push_back("Refresh Sources");
- stages.push_back("Rebuild Cache");
- stages.push_back("Load Data");
-
- PkgProgress pkgprogress(_callbackHandler);
-
- // 3 steps per repository (download, cache rebuild, load resolvables)
- pkgprogress.Start("Loading the Package Manager...", stages, "help");
-
- YCPValue ret = SourceLoadImpl(pkgprogress);
-
- pkgprogress.Done();
-
- return ret;
-}
-
-
-/****************************************************************************************
- * @builtin SourceLoad
- *
- * @short Load resolvables from the installation sources
- * @description
- * Refresh the pool - Add/remove resolvables from the enabled/disabled sources.
- * @return boolean True on success
- **/
-YCPValue
-PkgModuleFunctions::SourceLoadImpl(PkgProgress &progress)
-{
- bool success = true;
-
- int repos_to_load = 0;
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
- {
- repos_to_load++;
- }
- }
-
- // set max. value (3 steps per repository - refresh, rebuild, load)
- zypp::ProgressData prog_total(repos_to_load * 3);
- prog_total.sendTo(progress.Receiver());
-
- zypp::RepoManager repomanager = CreateRepoManager();
-
- // refresh metadata
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- // load resolvables only from enabled repos which are not deleted
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
- {
- // sub tasks
- zypp::CombinedProgressData refresh_subprogress(prog_total, 1);
-
- if (AnyResolvableFrom((*it)->repoInfo().alias()))
- {
- y2milestone("Resolvables from '%s' are already present, not loading", (*it)->repoInfo().alias().c_str());
- }
- else
- {
- // autorefresh the source
- if ((*it)->repoInfo().autorefresh())
- {
- try
- {
- y2milestone("Autorefreshing source: %s", (*it)->repoInfo().alias().c_str());
- RefreshWithCallbacks((*it)->repoInfo());
-
- zypp::ProgressData prog(1);
- prog.sendTo(refresh_subprogress);
- RefreshWithCallbacks((*it)->repoInfo());
- prog.toMax();
- }
- // NOTE: subtask progresses are reported as done in the descructor
- // no need to handle them in the exception code
- catch (const zypp::Exception& excpt)
- {
- y2error ("Error in SourceLoad: %s", excpt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- success = false;
- }
- }
- }
- }
- }
-
- progress.NextStage();
-
- // rebuild cache
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- // load resolvables only from enabled repos which are not deleted
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
- {
- // sub tasks
- zypp::CombinedProgressData rebuild_subprogress(prog_total, 1);
-
- if (AnyResolvableFrom((*it)->repoInfo().alias()))
- {
- y2milestone("Resolvables from '%s' are already present, not loading", (*it)->repoInfo().alias().c_str());
- }
- else
- {
- // autorefresh the source
- if ((*it)->repoInfo().autorefresh())
- {
- try
- {
- // rebuild cache (the default policy is "if needed")
- y2milestone("Rebuilding cache for '%s'...", (*it)->repoInfo().alias().c_str());
-
- zypp::ProgressData prog(1);
- prog.sendTo(rebuild_subprogress);
- repomanager.buildCache((*it)->repoInfo());
- prog.toMax();
- }
- // NOTE: subtask progresses are reported as done in the descructor
- // no need to handle them in the exception code
- catch (const zypp::Exception& excpt)
- {
- y2error ("Error in SourceLoad: %s", excpt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- success = false;
- }
- }
- }
- }
- }
-
- progress.NextStage();
-
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- // load resolvables only from enabled repos which are not deleted
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
- {
- // sub tasks
- zypp::CombinedProgressData load_subprogress(prog_total, 1);
-
- if (AnyResolvableFrom((*it)->repoInfo().alias()))
- {
- y2milestone("Resolvables from '%s' are already present, not loading", (*it)->repoInfo().alias().c_str());
- }
- else
- {
- zypp::ProgressData prog(1);
- prog.sendTo(load_subprogress);
-
- // load objects
- success = LoadResolvablesFrom((*it)->repoInfo()) && success;
-
- prog.toMax();
- }
- }
- }
-
- // report 100%
- prog_total.toMax();
-
- return YCPBoolean(success);
-}
-
-
-/****************************************************************************************
- * @builtin SourceStartManager
- *
- * @short Start the source manager - restore the sources and load the resolvables
- * @description
- * Calls SourceRestore(), if argument enable is true SourceLoad() is called.
- * @param boolean enable If true the resolvables are loaded from the enabled sources
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceStartManager (const YCPBoolean& enable)
-{
- PkgProgress pkgprogress(_callbackHandler);
-
- // display the progress only when 'enable' is true
- if (enable->value())
- {
- std::list<std::string> stages;
- stages.push_back("Load Sources");
- stages.push_back("Refresh Sources");
- stages.push_back("Rebuild Cache");
- stages.push_back("Load Data");
-
- // 3 steps per repository (download, cache rebuild, load resolvables)
- pkgprogress.Start("Loading the Package Manager...", stages, "help");
- }
-
- YCPValue ret = SourceStartManagerImpl(enable, pkgprogress);
-
- if (enable->value())
- {
- pkgprogress.Done();
- }
-
- return ret;
-}
-
-/****************************************************************************************
- * @builtin SourceStartManager
- *
- * @short Start the source manager - restore the sources and load the resolvables
- * @description
- * Calls SourceRestore(), if argument enable is true SourceLoad() is called.
- * @param boolean enable If true the resolvables are loaded from the enabled sources
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceStartManagerImpl(const YCPBoolean& enable, PkgProgress &progress)
-{
- YCPValue success = SourceRestore();
-
- progress.NextStage();
-
- if( enable->value() )
- {
- if (!success->asBoolean()->value())
- {
- y2warning("SourceStartManager: Some sources have not been restored, loading only the active sources...");
- }
-
- // enable all sources and load the resolvables
- success = YCPBoolean(SourceLoadImpl(progress)->asBoolean()->value() && success->asBoolean()->value());
- }
-
- return success;
-}
-
-/****************************************************************************************
- * @builtin SourceStartCache
- *
- * @short Make sure the InstSrcManager is up, and return the list of SrcIds.
- * @description
- * Make sure the InstSrcManager is up, and return the list of SrcIds.
- * In fact nothing more than:
- *
- * <code>
- * SourceStartManager( enabled_only );
- * return SourceGetCurrent( enabled_only );
- * </code>
- *
- * @param boolean enabled_only If true, make sure all InstSrces are enabled according to
- * their default, and return the Ids of enabled InstSrces only. If false, return
- * the Ids of all known InstSrces.
- *
- * @return list<integer> list of SrcIds
- **/
-YCPValue
-PkgModuleFunctions::SourceStartCache (const YCPBoolean& enabled)
-{
- try
- {
- SourceStartManager(enabled);
-
- return SourceGetCurrent(enabled);
- }
- catch (const zypp::Exception& excpt)
- {
- y2error ("Error in SourceStartCache: %s", excpt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- }
- // catch an exception from boost (e.g. a file cannot be read by non-root user)
- catch (const std::exception& err)
- {
- y2error ("Error in SourceStartCache: %s", err.what());
- _last_error.setLastError(err.what());
- }
- catch (...)
- {
- y2error("Unknown error in SourceStartCache");
- }
-
- return YCPList();
-}
-
-/****************************************************************************************
- * @builtin SourceCleanupBroken
- *
- * @short Clean up all sources that were not properly restored on the last
- * call of SourceStartManager or SourceStartCache.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceCleanupBroken ()
-{
- y2warning("Pkg::SourceCleanupBroken() is obsoleted, it's not needed anymore.");
- return YCPBoolean(true);
-}
-
-/****************************************************************************************
- * @builtin SourceGetCurrent
- *
- * @short Return the list of all InstSrc Ids.
- *
- * @param boolean enabled_only If true, or omitted, return the Ids of all enabled InstSrces.
- * If false, return the Ids of all known InstSrces.
- *
- * @return list<integer> list of SrcIds (integer)
- **/
-YCPValue
-PkgModuleFunctions::SourceGetCurrent (const YCPBoolean& enabled)
-{
- YCPList res;
-
- std::vector<YRepo_Ptr>::size_type index = 0;
- for( std::vector<YRepo_Ptr>::const_iterator it = repos.begin(); it != repos.end() ; ++it, ++index )
- {
- // ignore disabled sources if requested
- if (enabled->value())
- {
- // Note: enabled() is tribool!
- if ((*it)->repoInfo().enabled())
- {
- }
- else if (!(*it)->repoInfo().enabled())
- {
- continue;
- }
- else
- {
- continue;
- }
- }
-
- // ignore deleted sources
- if ((*it)->isDeleted())
- {
- continue;
- }
-
- res->add( YCPInteger(index) );
- }
-
- return res;
-}
-
-/****************************************************************************************
- * @builtin SourceReleaseAll
- *
- * @short Release all medias hold by all sources
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceReleaseAll ()
-{
- y2milestone("Releasing all sources...");
- bool ret = true;
-
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- try
- {
- (*it)->mediaAccess()->release();
- }
- catch (const zypp::media::MediaException & ex)
- {
- y2warning("Failed to release media for repo: %s", ex.msg().c_str());
- ret = false;
- }
- }
-
- return YCPBoolean(ret);
-}
-
-/******************************************************************************
- * @builtin SourceSaveAll
- *
- * @short Save all InstSrces.
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceSaveAll ()
-{
- y2milestone("Saving the source setup...");
-
- zypp::RepoManager repomanager = CreateRepoManager();
-
- // remove deleted repos (the old configurations) at first
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- // the repo has been removed
- if ((*it)->isDeleted())
- {
- std::string repo_alias = (*it)->repoInfo().alias();
-
- try
- {
- // remove the metadata
- zypp::RepoStatus raw_metadata_status = repomanager.metadataStatus((*it)->repoInfo());
- if (!raw_metadata_status.empty())
- {
- y2milestone("Removing metadata for source '%s'...", repo_alias.c_str());
- repomanager.cleanMetadata((*it)->repoInfo());
- }
-
- // remove the cache
- if (repomanager.isCached((*it)->repoInfo()))
- {
- y2milestone("Removing cache for '%s'...", repo_alias.c_str());
- repomanager.cleanCache((*it)->repoInfo());
- }
-
- repomanager.getRepositoryInfo(repo_alias);
- y2milestone("Removing repository '%s'", repo_alias.c_str());
- repomanager.removeRepository((*it)->repoInfo());
- }
- catch (const zypp::repo::RepoNotFoundException &ex)
- {
- // repository not found -- not critical, continue
- y2warning("No such repository: %s", repo_alias.c_str());
- }
- catch (const zypp::Exception & excpt)
- {
- y2error("Pkg::SourceSaveAll has failed: %s", excpt.msg().c_str() );
- _last_error.setLastError(ExceptionAsString(excpt));
- return YCPBoolean(false);
- }
- }
- }
-
- // save all repos (the current configuration)
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- if (!(*it)->isDeleted())
- {
- std::string current_alias = (*it)->repoInfo().alias();
-
- try
- {
- try
- {
- // if the repository already exists then just modify it
- repomanager.getRepositoryInfo(current_alias);
- y2milestone("Modifying repository '%s'", current_alias.c_str());
- repomanager.modifyRepository(current_alias, (*it)->repoInfo());
- }
- catch (const zypp::repo::RepoNotFoundException &ex)
- {
- // the repository was not found, add it
- y2milestone("Adding repository '%s'", current_alias.c_str());
- repomanager.addRepository((*it)->repoInfo());
- }
- }
- catch (zypp::Exception & excpt)
- {
- y2error("Pkg::SourceSaveAll has failed: %s", excpt.msg().c_str() );
- _last_error.setLastError(ExceptionAsString(excpt));
- return YCPBoolean(false);
- }
- }
- }
-
- y2milestone("All sources have been saved");
-
- return YCPBoolean(true);
-}
-
-/****************************************************************************************
- * @builtin SourceFinishAll
- *
- * @short Save and then disable all InstSrces.
- * @description
- * If there are no enabled sources, do nothing
- * (idempotence hack, broken design: #155459, #176013, use SourceSaveAll).
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceFinishAll ()
-{
- try
- {
- bool found_enabled = false;
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
- {
- found_enabled = true;
- break;
- }
- }
-
- if (!found_enabled)
- {
- y2milestone( "No enabled sources, skipping SourceFinishAll()" );
- return YCPBoolean( true );
- }
-
- SourceSaveAll();
-
- y2milestone( "Disabling all sources...") ;
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- (*it)->repoInfo().setEnabled(false);
- }
- // TODO FIXME remove all resolvables??
- }
- catch (zypp::Exception & excpt)
- {
- y2error("Pkg::SourceFinishAll has failed: %s", excpt.msg().c_str() );
- _last_error.setLastError(ExceptionAsString(excpt));
- return YCPBoolean(false);
- }
-
- y2milestone("All sources have been saved and disabled");
-
- return YCPBoolean(true);
-}
-
-/////////////////////////////////////////////////////////////////////////////////////////
-// Query individual sources
-/////////////////////////////////////////////////////////////////////////////////////////
-
-/****************************************************************************************
- * @builtin SourceGeneralData
- *
- * @short Get general data about the source
- * @description
- * Return general data about the source as a map:
- *
- * <code>
- * $[
- * "enabled" : YCPBoolean,
- * "autorefresh": YCPBoolean,
- * "product_dir": YCPString,
- * "type" : YCPString,
- * "url" : YCPString (without password, but see SourceURL),
- * "alias" : YCPString,
- * "name" : YCPString,
- * ];
- *
- * </code>
- * @param integer SrcId Specifies the InstSrc to query.
- * @return map
- **/
-YCPValue
-PkgModuleFunctions::SourceGeneralData (const YCPInteger& id)
-{
- YCPMap data;
-
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPVoid ();
-
- // convert type to the old strings ("YaST", "YUM" or "Plaindir")
- std::string srctype = zypp2yastType(repo->repoInfo().type().asString());
-
- data->add( YCPString("enabled"), YCPBoolean(repo->repoInfo().enabled()));
- data->add( YCPString("autorefresh"), YCPBoolean(repo->repoInfo().autorefresh()));
- data->add( YCPString("type"), YCPString(srctype));
- data->add( YCPString("product_dir"), YCPString(repo->repoInfo().path().asString()));
-
- // check if there is an URL
- if (repo->repoInfo().baseUrlsBegin() != repo->repoInfo().baseUrlsEnd())
- {
- data->add( YCPString("url"), YCPString(repo->repoInfo().baseUrlsBegin()->asString()));
- }
-
- data->add( YCPString("alias"), YCPString(repo->repoInfo().alias()));
- data->add( YCPString("name"), YCPString(repo->repoInfo().name()));
-
- YCPList base_urls;
- for( zypp::RepoInfo::urls_const_iterator it = repo->repoInfo().baseUrlsBegin(); it != repo->repoInfo().baseUrlsEnd(); ++it)
- {
- base_urls->add(YCPString(it->asString()));
- }
- data->add( YCPString("base_urls"), base_urls);
-
- data->add( YCPString("mirror_list"), YCPString(repo->repoInfo().mirrorListUrl().asString()));
-
- return data;
-}
-
-/******************************************************************************
- * @builtin SourceURL
- *
- * @short Get full source URL, including password
- * @param integer SrcId Specifies the InstSrc to query.
- * @return string or nil on failure
- **/
-YCPValue
-PkgModuleFunctions::SourceURL (const YCPInteger& id)
-{
-
- const YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPVoid();
-
- std::string url;
-
- if (repo->repoInfo().baseUrlsBegin() != repo->repoInfo().baseUrlsEnd())
- {
- // #186842
- url = repo->repoInfo().baseUrlsBegin()->asCompleteString();
- }
-
- return YCPString(url);
-}
-
-/****************************************************************************************
- * @builtin SourceMediaData
- * @short Return media data about the source
- * @description
- * Return media data about the source as a map:
- *
- * <code>
- * $["media_count": YCPInteger,
- * "media_id" : YCPString,
- * "media_vendor" : YCPString,
- * "url" : YCPString,
- * ];
- * </code>
- *
- * @param integer SrcId Specifies the InstSrc to query.
- * @return map
- **/
-YCPValue
-PkgModuleFunctions::SourceMediaData (const YCPInteger& id)
-{
- YCPMap data;
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPVoid ();
-
- std::string alias = repo->repoInfo().alias();
- bool found_resolvable = false;
- int max_medium = 1;
-
- for (zypp::ResPool::const_iterator it = zypp_ptr()->pool().begin()
- ; it != zypp_ptr()->pool().end()
- ; ++it)
- {
- if (it->resolvable()->repository().info().alias() == alias)
- {
- int medium = it->resolvable()->mediaNr();
-
- if (medium > max_medium)
- {
- max_medium = medium;
- }
- }
- }
-
- if (found_resolvable)
- {
- data->add( YCPString("media_count"), YCPInteger(max_medium));
- }
- else
- {
- y2error("No resolvable from repository '%s' found, cannot get number of media (use Pkg::SourceLoad() to load the resolvables)", alias.c_str());
- }
-
- y2warning("Pkg::SourceMediaData() doesn't return \"media_id\" and \"media_vendor\" values anymore.");
-
- // SourceMediaData returns URLs without password
- if (repo->repoInfo().baseUrlsBegin() != repo->repoInfo().baseUrlsEnd())
- {
- data->add( YCPString("url"), YCPString(repo->repoInfo().baseUrlsBegin()->asString()));
-
- // add all base URLs
- YCPList base_urls;
- for( zypp::RepoInfo::urls_const_iterator it = repo->repoInfo().baseUrlsBegin(); it != repo->repoInfo().baseUrlsEnd(); ++it)
- {
- base_urls->add(YCPString(it->asString()));
- }
- data->add( YCPString("base_urls"), base_urls);
- }
-
- return data;
-}
-
-/****************************************************************************************
- * @builtin SourceProductData
- * @short Return Product data about the source
- * @param integer SrcId Specifies the InstSrc to query.
- * @description
- * Product data about the source as a map:
- *
- * <code>
- * $[
- * "label" : YCPString,
- * "vendor" : YCPString,
- * "productname" : YCPString,
- * "productversion" : YCPString,
- * "relnotesurl" : YCPString,
- * ];
- * </code>
- *
- * @return map
- **/
-YCPValue
-PkgModuleFunctions::SourceProductData (const YCPInteger& src_id)
-{
- YCPMap ret;
-
- try
- {
- // find a product for the given source
- zypp::ResPool::byKind_iterator it = zypp_ptr()->pool().byKindBegin(zypp::ResTraits<zypp::Product>::kind);
-
- for( ; it != zypp_ptr()->pool().byKindEnd(zypp::ResTraits<zypp::Product>::kind) ; ++it)
- {
- zypp::Product::constPtr product = boost::dynamic_pointer_cast<const zypp::Product>( it->resolvable() );
-
- if( logFindAlias(product->repository().info().alias()) == src_id->value() )
- {
- ret->add( YCPString("label"), YCPString( product->summary() ) );
- ret->add( YCPString("vendor"), YCPString( product->vendor() ) );
- ret->add( YCPString("productname"), YCPString( product->name() ) );
- ret->add( YCPString("productversion"), YCPString( product->edition().version() ) );
- ret->add( YCPString("relnotesurl"), YCPString( product->releaseNotesUrl().asString()));
-
- #warning SourceProductData not finished
- /*
- data->add( YCPString("datadir"), YCPString( descr->content_datadir().asString() ) );
- TODO (?): "baseproductname", "baseproductversion", "defaultbase", "architectures",
- "requires", "linguas", "labelmap", "language", "timezone", "descrdir", "datadir"
- */
-
- break;
- }
- }
-
- if( it == zypp_ptr()->pool().byKindEnd(zypp::ResTraits<zypp::Product>::kind) )
- {
- y2error ("Product for source '%lld' not found", src_id->value());
- }
- }
- catch (...)
- {
- }
-
- return ret;
-}
-
-/****************************************************************************************
- * @builtin SourceProduct
- * @short Obsoleted function, do not use, see SourceProductData builtin
- * @deprecated
- * @param integer
- * @return map empty map
- **/
-YCPValue
-PkgModuleFunctions::SourceProduct (const YCPInteger& id)
-{
- /* TODO FIXME */
- y2error("Pkg::SourceProduct() is obsoleted, use Pkg::SourceProductData() instead!");
- return YCPMap();
-}
-
-
-YCPValue PkgModuleFunctions::SourceProvideFileCommon(const YCPInteger &id,
- const YCPInteger &mid,
- const YCPString& f,
- const YCPBoolean & optional)
-{
- CallInitDownload(std::string(_("Downloading ") + f->value()));
-
- bool found = true;
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- found = false;
-
- extern ZyppRecipients::MediaChangeSensitivity _silent_probing;
- // remember the current value
- ZyppRecipients::MediaChangeSensitivity _silent_probing_old = _silent_probing;
-
- // disable media change callback for optional file
- if (optional->value())
- _silent_probing = ZyppRecipients::MEDIA_CHANGE_OPTIONALFILE;
-
- zypp::filesystem::Pathname path; // FIXME use ManagedMedia
- if (found)
- {
- try
- {
- path = repo->mediaAccess()->provideFile(f->value(), mid->value());
- y2milestone("local path: '%s'", path.asString().c_str());
- }
- catch (const zypp::Exception& excpt)
- {
- found = false;
-
- if (!optional->value())
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2milestone("File not found: %s", f->value_cstr());
- }
- }
- }
-
- // set the original probing value
- _silent_probing = _silent_probing_old;
-
- CallDestDownload();
-
- if (found)
- {
- return YCPString(path.asString());
- }
- else
- {
- return YCPVoid();
- }
-}
-
-
-/****************************************************************************************
- * @builtin SourceProvideFile
- *
- * @short Make a file available at the local filesystem
- * @description
- * Let an InstSrc provide some file (make it available at the local filesystem).
- *
- * @param integer SrcId Specifies the InstSrc .
- * @param integer medianr Number of the media the file is located on ('1' for the 1st media).
- * @param string file Filename relative to the media root.
- *
- * @return string local path as string
- **/
-YCPValue
-PkgModuleFunctions::SourceProvideFile (const YCPInteger& id, const YCPInteger& mid, const YCPString& f)
-{
- return SourceProvideFileCommon(id, mid, f, false /*optional*/);
-}
-
-/****************************************************************************************
- * @builtin SourceProvideOptionalFile
- *
- * @short Make an optional file available at the local filesystem
- * @description
- * Let an InstSrc provide some file (make it available at the local filesystem).
- * If the file doesn't exist don't ask user for another medium and return nil
- *
- * @param integer SrcId Specifies the InstSrc .
- * @param integer medianr Number of the media the file is located on ('1' for the 1st media).
- * @param string file Filename relative to the media root.
- *
- * @return string local path as string
- **/
-YCPValue
-PkgModuleFunctions::SourceProvideOptionalFile (const YCPInteger& id, const YCPInteger& mid, const YCPString& f)
-{
- return SourceProvideFileCommon(id, mid, f, true /*optional*/);
-}
-
-/****************************************************************************************
- * @builtin SourceProvideDir
- * @short make a directory available at the local filesystem
- * @description
- * Let an InstSrc provide some directory (make it available at the local filesystem) and
- * all the files within it (non recursive).
- *
- * @param integer SrcId Specifies the InstSrc .
- * @param integer medianr Number of the media the file is located on ('1' for the 1st media).
- * @param string dir Directoryname relative to the media root.
- * @return string local path as string
- */
-YCPValue
-PkgModuleFunctions::SourceProvideDir (const YCPInteger& id, const YCPInteger& mid, const YCPString& d)
-{
- y2warning("Pkg::SourceProvideDir() is obsoleted use Pkg::SourceProvideDirectory() instead");
- // non optional, non recursive
- return SourceProvideDirectory(id, mid, d, false, false);
-}
-
-
-/****************************************************************************************
- * @builtin SourceProvideDirectory
- * @short make a directory available at the local filesystem
- * @description
- * Download a directory from repository (make it available at the local filesystem) and
- * all the files within it.
- *
- * @param integer id repository to use (id)
- * @param integer mid Number of the media where the directory is located on ('1' for the 1st media).
- * @param string d Directory name relative to the media root.
- * @param boolean optional set to true if the directory may not exist (do not report errors)
- * @param boolean recursive set to true to provide all subdirectories recursively
- * @return string local path as string or nil when an error occured
- */
-YCPValue
-PkgModuleFunctions::SourceProvideDirectory(const YCPInteger& id, const YCPInteger& mid, const YCPString& d, const YCPBoolean &optional, const YCPBoolean &recursive)
-{
- CallInitDownload(std::string(_("Downloading ") + d->value()));
-
- bool found = true;
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- found = false;
-
- zypp::filesystem::Pathname path; // FIXME user ManagedMedia
-
- extern ZyppRecipients::MediaChangeSensitivity _silent_probing;
- // remember the current value
- ZyppRecipients::MediaChangeSensitivity _silent_probing_old = _silent_probing;
-
- // disable media change callback for optional file
- if (optional->value())
- _silent_probing = ZyppRecipients::MEDIA_CHANGE_OPTIONALFILE;
-
- if (found)
- {
- try
- {
- path = repo->mediaAccess()->provideDir(d->value(), recursive->value(), mid->value());
- }
- catch (const zypp::Exception& excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2milestone ("Directory not found: %s", d->value_cstr());
- found = false;
- }
- }
-
- // set the original probing value
- _silent_probing = _silent_probing_old;
-
- CallDestDownload();
-
- if (found)
- {
- return YCPString(path.asString());
- }
- else
- {
- return YCPVoid();
- }
-}
-
-/****************************************************************************************
- * @builtin SourceChangeUrl
- * @short Change Source URL
- * @description
- * Change url of an InstSrc. Used primarely when re-starting during installation
- * and a cd-device changed from hdX to srX since ide-scsi was activated.
- * @param integer SrcId Specifies the InstSrc.
- * @param string url The new url to use.
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceChangeUrl (const YCPInteger& id, const YCPString& u)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- try
- {
- if (repo->repoInfo().baseUrlsSize() > 1)
- {
- // store current urls
- std::set<zypp::Url> baseUrls (repo->repoInfo().baseUrlsBegin(), repo->repoInfo().baseUrlsEnd());
-
- // reset url list and store the new one there
- repo->repoInfo().setBaseUrl(zypp::Url(u->value()));
-
- // add the rest of base urls
- for (std::set<zypp::Url>::const_iterator i = baseUrls.begin();
- i != baseUrls.end(); ++i)
- repo->repoInfo().addBaseUrl(*i);
- }
- else
- repo->repoInfo().setBaseUrl(zypp::Url(u->value()));
- }
- catch (const zypp::Exception & excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error ("Cannot set the new URL for source %s (%lld): %s",
- repo->repoInfo().alias().c_str(), id->asInteger()->value(), excpt.msg().c_str());
- return YCPBoolean(false);
- }
-
- return YCPBoolean(true);
-}
-
-/****************************************************************************************
- * @builtin SourceInstallOrder
- *
- * @short not implemented, do not use (Explicitly set an install order.)
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceInstallOrder (const YCPMap& ord)
-{
- /* TODO FIXME
- YCPList args;
- args->add (ord);
-
- //-------------------------------------------------------------------------------------//
- YcpArgLoad decl(__FUNCTION__);
-
- YCPMap & order_map( decl.arg<YT_MAP, YCPMap>() );
-
- if ( ! decl.load( args ) ) {
- return pkgError_bad_args;
- }
- //-------------------------------------------------------------------------------------//
-
- InstSrcManager::InstOrder order;
- order.reserve( order_map->size() );
- bool error = false;
-
- for ( YCPMapIterator it = order_map->begin(); it != order_map->end(); ++it ) {
-
- if ( it.value()->isInteger() ) {
- InstSrc::UniqueID uId( it.value()->asInteger()->value() );
- InstSrcManager::ISrcId source_id( _y2pm.instSrcManager().getSourceByID( uId ) );
- if ( source_id ) {
- if ( source_id->enabled() ) {
- order.push_back( uId ); // finaly ;)
-
- } else {
- y2error ("order map entry '%s:%s': source not enabled",
- it.key()->toString().c_str(),
- it.value()->toString().c_str() );
- error = true;
- }
- } else {
- y2error ("order map entry '%s:%s': bad source id",
- it.key()->toString().c_str(),
- it.value()->toString().c_str() );
- error = true;
- }
- } else {
- y2error ("order map entry '%s:%s': integer value expected",
- it.key()->toString().c_str(),
- it.value()->toString().c_str() );
- error = true;
- }
- }
- if ( error ) {
- return pkgError( Error::E_bad_args );
- }
-
- // store new instorder
- _y2pm.instSrcManager().setInstOrder( order );
-*/
-
-#warning SourceInstallOrder is not implemented
- return YCPBoolean( true );
-}
-
-
-static std::string timestamp ()
-{
- time_t t = time(NULL);
- struct tm * tmp = localtime(&t);
-
- if (tmp == NULL) {
- return "";
- }
-
- char outstr[50];
- if (strftime(outstr, sizeof(outstr), "%Y%m%d-%H%M%S", tmp) == 0) {
- return "";
- }
- return outstr;
-}
-
-/**
- * Take the ?alias=foo part of old_url, if any, and return it,
- * putting the rest to new_url.
- * \throws Exception on malformed URLs I guess
- */
-static std::string removeAlias (const zypp::Url & old_url,
- zypp::Url & new_url)
-{
- std::string alias;
- new_url = old_url;
- zypp::url::ParamMap query = new_url.getQueryStringMap ();
- zypp::url::ParamMap::iterator alias_it = query.find ("alias");
- if (alias_it != query.end ())
- {
- alias = alias_it->second;
- query.erase (alias_it);
- new_url.setQueryStringMap (query);
- }
- return alias;
-}
-
-std::string PkgModuleFunctions::UniqueAlias(const std::string &alias)
-{
- // make a copy
- std::string ret = alias;
-
- unsigned int id = 0;
- while(aliasExists(ret))
- {
- y2milestone("Alias %s already found: %lld", ret.c_str(), logFindAlias(ret));
-
- // the alias already exists - add a counter
- std::ostringstream ostr;
- ostr << alias << "_" << id;
-
- ret = ostr.str();
-
- y2milestone("Using alias %s", ret.c_str());
- ++id;
- }
-
- return ret;
-}
-
-
-/**
- * helper - add "mountoptions=ro" for mountable URL schemes if "mountoptions" option is not empty and
- * "rw" or "ro" option is missing
- */
-zypp::Url addRO(const zypp::Url &url)
-{
- zypp::Url ret(url);
- std::string scheme = zypp::str::toLower(url.getScheme());
-
- if (scheme == "nfs"
- || scheme == "hd"
- || scheme == "smb"
- || scheme == "iso"
- || scheme == "cd"
- || scheme == "dvd"
- )
- {
- const std::string mountoptions = "mountoptions";
- zypp::media::Mount::Options options(url.getQueryParam(mountoptions));
-
- y2debug("Current mountoptions: %s", options.asString().c_str());
-
- // if mountoptions are empty lizypp uses "ro" by default
- // don't override "rw" option from application
- // don't add "ro" if it's already present
- if (!options.empty() && !options.has("rw") && !options.has("ro"))
- {
- options["ro"];
-
- ret.setQueryParam(mountoptions, options.asString());
- y2milestone("Adding read only mount option: '%s' -> '%s'", url.asString().c_str(), ret.asString().c_str());
- }
- }
-
- return ret;
-}
-
-// helper function
-zypp::Url PkgModuleFunctions::shortenUrl(const zypp::Url &url)
-{
- std::string url_path = url.getPathName();
- std::string begin_path;
- std::string end_path;
-
- // try to convert 'http://server/dir1/dir2/dir3/dir4' -> 'http://server/dir1/.../dir4'
- std::string::size_type pos_first = url_path.find("/");
- if (pos_first == 0)
- {
- pos_first = url_path.find("/", 1);
- }
-
- if (pos_first == std::string::npos)
- {
- const int num = 5;
-
- // "/" not found use the beginning and the end part
- // 'http://server/very_long_directory_name' -> 'http://server/very_..._name'
- begin_path = std::string(url_path, 0, num);
- end_path = std::string(url_path, url_path.size() - num - 1, num);
- }
- else
- {
- unsigned int pos_last = url_path.rfind("/");
- if (pos_last == url_path.size() - 1)
- {
- pos_last = url_path.rfind("/", url_path.size() - 1);
- }
-
- if (pos_last == pos_first || pos_last < pos_first)
- {
- const int num = 5;
-
- // "/" not found use the beginning and the end part
- begin_path = std::string(url_path, 0, num);
- end_path = std::string(url_path, url_path.size() - num - 1, num);
- }
- else
- {
- begin_path = std::string(url_path, 0, pos_first + 1);
- end_path = std::string(url_path, pos_last);
- }
- }
-
- std::string new_path = begin_path + "..." + end_path;
- zypp::Url ret(url);
-
- // use the shorter path
- ret.setPathName(new_path);
- // remove query parameters
- ret.setQueryString("");
- // remove fragmet
- ret.setFragment("");
-
- y2milestone("Using shortened URL: '%s' -> '%s'", url.asString().c_str(), ret.asString().c_str());
- return ret;
-}
-
-/** Create a Source and immediately put it into the SourceManager.
- * \return the SourceId
- * \throws Exception if Source creation fails
-*/
-std::vector<zypp::RepoInfo>::size_type
-PkgModuleFunctions::createManagedSource( const zypp::Url & url_r,
- const zypp::Pathname & path_r,
- const bool base_source,
- const std::string& type,
- const std::string &alias_r )
-{
- // parse URL
- y2milestone ("Original URL: %s, product directory: %s", url_r.asString().c_str(), path_r.asString().c_str());
-
- // #158850#c17, if the URL contains an alias, we use that
- zypp::Url url;
-
- std::string alias = removeAlias(url_r, url);
- y2milestone("Alias from URL: '%s'", alias.c_str());
-
-#warning FIXME: use base_source (base_source vs. addon) (will be probably not needed)
-
- // repository type
- zypp::repo::RepoType repotype;
- zypp::RepoManager repomanager = CreateRepoManager();
-
- if (!type.empty())
- {
- try
- {
- // do conversion from the Yast type ("YaST", "YUM", "Plaindir")
- // to libzypp type ("yast", "yum", "plaindir")
- repotype = repotype.parse(yast2zyppType(type));
- }
- catch (zypp::repo::RepoUnknownTypeException &e)
- {
- y2warning("Unknown source type '%s'", type.c_str());
- }
- }
-
- // the type is not specified or is wrong, autoprobe the type
- if (repotype == zypp::repo::RepoType::NONE)
- {
- zypp::Url probe_url(url_r);
-
- if (!path_r.asString().empty())
- {
- zypp::Pathname pth(probe_url.getPathName());
- pth /= path_r;
-
- probe_url.setPathName(pth.asString());
- }
-
- y2milestone("Probing source type: '%s'", probe_url.asString().c_str());
-
- // autoprobe type of the repository
- repotype = ProbeWithCallbacks(probe_url);
- }
-
- y2milestone("Using source type: %s", repotype.asString().c_str());
-
-
- // create source definition object
- zypp::RepoInfo repo;
-
- std::string name;
-
- // set alias and name
- if (alias.empty())
- {
- // alias not set via URL, use the passed alias or the URL path
- if (alias_r.empty())
- {
- // use the last path element in URL
- std::string url_path = url.getPathName();
-
- std::string::size_type pos_begin = url_path.rfind("/");
- std::string::size_type pos_end = std::string::npos;
-
- // ignore the trailing slash
- if (pos_begin == url_path.size() - 1)
- {
- pos_begin = url_path.rfind("/", url_path.size() - 2);
-
- if (pos_begin != std::string::npos)
- {
- pos_end = url_path.size() - pos_begin - 2;
- }
- }
- else
- {
- pos_end = url_path.size() - pos_begin - 1;
- }
-
- // ignore the found slash character
- pos_begin++;
-
- alias = std::string(url_path, pos_begin, pos_end);
-
- y2milestone("Alias from URL path: %s", alias.c_str());
-
- // fallback
- if (alias.empty())
- {
- y2milestone("URL alias is empty using 'Repository'");
- alias = "Repository";
- }
- }
- else
- {
- alias = alias_r;
- }
-
- name = alias;
- }
- else
- {
- name = alias;
- }
-
-
- y2milestone("Name of the repository: '%s'", name.c_str());
-
- // alias must be unique, add a suffix if it's already used
- alias = UniqueAlias(alias);
-
- // add read only mount option to the URL if needed
- url = addRO(url);
-
- bool autorefresh = true;
-
- std::string scheme = zypp::str::toLower(url.getScheme());
- if (scheme == "cd" || scheme == "dvd")
- {
- y2milestone("Disabling autorefresh for CD/DVD repository");
- autorefresh = false;
- }
-
- repo.setAlias(alias);
- repo.setName(name);
- repo.setType(repotype);
- repo.addBaseUrl(url);
- repo.setPath(path_r);
- repo.setEnabled(true);
- repo.setAutorefresh(autorefresh);
-
- // set metadata path (#293428)
- zypp::Pathname metadatapath = repomanager.metadataPath(repo);
- repo.setMetadataPath(metadatapath);
-
- y2milestone("Adding source '%s' (%s, dir: %s)", repo.alias().c_str(), url.asString().c_str(), path_r.asString().c_str());
- // note: exceptions should be caught by the calling code
- RefreshWithCallbacks(repo);
-
- // build cache if needed
- if (!repomanager.isCached(repo))
- {
- y2milestone("Caching source '%s'...", repo.alias().c_str());
- repomanager.buildCache(repo);
- }
-
- repos.push_back(new YRepo(repo));
-
- y2milestone("Added source '%s': '%s', enabled: %s, autorefresh: %s",
- repo.alias().c_str(),
- repo.baseUrlsBegin()->asString().c_str(),
- repo.enabled() ? "true" : "false",
- repo.autorefresh() ? "true" : "false"
- );
-
- // the source is at the end of the list
- return repos.size() - 1;
-}
-
-/****************************************************************************************
- * @builtin RepositoryAdd
- *
- * @short Register a new repository
- * @description
- * Adds a new repository to the internal structures. The repository is only registered,
- * metadata is not downloaded, use Pkg::SourceRefreshNow() for that. The metadata is also loaded
- * automatically when loading the repository content (Pkg::SourceLoad())
- *
- * @param map map with repository parameters: $[ "enabled" : boolean, "autorefresh" : boolean, "name" : string,
- * "alias" : string, "base_urls" : list<string>, "prod_dir" : string, "type" : string ]
- * @return integer Repository ID or nil on error
- **/
-YCPValue PkgModuleFunctions::RepositoryAdd(const YCPMap ¶ms)
-{
- zypp::RepoInfo repo;
-
- // turn on the repo by default
- repo.setEnabled(true);
- // enable autorefresh by default
- repo.setAutorefresh(true);
-
- if (!params->value( YCPString("enabled") ).isNull() && params->value(YCPString("enabled"))->isBoolean())
- {
- repo.setEnabled(params->value(YCPString("enabled"))->asBoolean()->value());
- }
-
- if (!params->value( YCPString("autorefresh") ).isNull() && params->value(YCPString("autorefresh"))->isBoolean())
- {
- repo.setAutorefresh(params->value(YCPString("autorefresh"))->asBoolean()->value());
- }
-
- std::string alias;
-
- if (!params->value( YCPString("alias") ).isNull() && params->value(YCPString("alias"))->isString())
- {
- alias = params->value(YCPString("alias"))->asString()->value();
- }
-
- if (alias.empty())
- {
- alias = timestamp();
-
- // the alias must be unique
- alias = UniqueAlias(alias);
- }
- else
- {
- if (aliasExists(alias))
- {
- ycperror("alias %s already exists", alias.c_str());
- return YCPVoid();
- }
- }
-
- repo.setAlias(alias);
-
- // use the first base URL as a fallback name
- std::string first_url;
-
- if (!params->value( YCPString("base_urls") ).isNull() && params->value(YCPString("base_urls"))->isList())
- {
- YCPList lst(params->value(YCPString("base_urls"))->asList());
-
- for (int index = 0; index < lst->size(); ++index)
- {
- if( ! lst->value(index)->isString() )
- {
- ycperror( "Pkg::RepositoryAdd(): entry not a string at index %d: %s", index, lst->toString().c_str());
- return YCPVoid();
- }
-
- zypp::Url url;
-
- try
- {
- url = lst->value(index)->asString()->value();
- zypp::Url url_new;
-
- std::string name = removeAlias(url, url_new);
-
- if (!name.empty())
- {
- repo.setName(name);
- url = url_new;
- }
-
- // add read only mount option to the URL if needed
- url = addRO(url);
- }
- catch(const zypp::Exception & expt)
- {
- y2error("Invalid URL: %s", expt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(expt));
- return YCPVoid();
- }
-
- if (index == 0)
- {
- first_url = url.asString();
- }
-
- repo.addBaseUrl(url);
- }
- }
- else
- {
- ycperror("Missing \"base_urls\" key in the map");
- return YCPVoid();
- }
-
- // check name parameter
- if (!params->value( YCPString("name") ).isNull() && params->value(YCPString("name"))->isString())
- {
- repo.setName(params->value(YCPString("name"))->asString()->value());
- }
- else
- {
- // if the key "name" is missing and the name hasn't been set by ?alias= in the URL
- // then use the first URL as the name
- if (repo.name().empty())
- {
- repo.setName(first_url);
- }
- }
-
- if (!params->value( YCPString("type") ).isNull() && params->value(YCPString("type"))->isString())
- {
- std::string type = yast2zyppType(params->value(YCPString("type"))->asString()->value());
-
- try
- {
- zypp::repo::RepoType repotype(type);
- repo.setType(repotype);
- }
- catch (zypp::repo::RepoUnknownTypeException &e)
- {
- ycperror("Unknown source type '%s': %s", type.c_str(), e.asString().c_str());
- _last_error.setLastError(ExceptionAsString(e));
- return YCPVoid();
- }
-
- }
-
- if (!params->value( YCPString("prod_dir") ).isNull() && params->value(YCPString("prod_dir"))->isString())
- {
- repo.setPath(params->value(YCPString("prod_dir"))->asString()->value());
- }
-
- // set metadata path (#293428)
- zypp::RepoManager repomanager = CreateRepoManager();
- zypp::Pathname metadatapath = repomanager.metadataPath(repo);
- repo.setMetadataPath(metadatapath);
-
- repos.push_back(new YRepo(repo));
-
- // the new source is at the end of the list
- return YCPInteger(repos.size() - 1);
-}
-
-/****************************************************************************************
- * @builtin SourceCacheCopyTo
- *
- * @short Copy cache data of all installation sources to the target
- * @description
- * Copy cache data of all installation sources to the target located below 'dir'.
- * To be called at end of initial installation.
- *
- * @param string dir Root directory of target.
- * @return boolean true on success
- **/
-YCPValue
-PkgModuleFunctions::SourceCacheCopyTo (const YCPString& dir)
-{
- // error message (followed by detailed description)
- const std::string msg = _("Error: Cannot copy the cache to the target directory\n");
-
- std::string d = dir->value();
- y2milestone("Copying source cache to '%s'...", d.c_str());
-
- if (d.empty())
- {
- y2error("Empty parameter in Pkg::SourceCacheCopyTo()!");
- return YCPBoolean(false);
- }
-
- std::string target = d + "/var/cache";
-
- // create the target dir
- const char* argv[] =
- {
- "mkdir",
- // create parent dir
- "-p",
- // finish parameter list
- "--",
- // target
- target.c_str(),
- NULL
- };
-
- // discard stderr, no pty, stderr_fd = -1, use the default locale
- zypp::ExternalProgram prog(argv, zypp::ExternalProgram::Discard_Stderr, false, -1, true);
-
- int code = prog.close();
-
- if (code)
- {
- // error message (followed by directory name)
- _last_error.setLastError(msg + _("Cannot create directory ") + target);
- y2error("Cannot create target directory %s", target.c_str());
- return YCPBoolean(false);
- }
-
- // copy /var/cache/zypp to the target system
- const char* argv2[] =
- {
- "cp",
- // preserve time stamps
- "-a",
- // recursive
- "-r",
- // finish parameter list
- "--",
- // source
- "/var/cache/zypp",
- // target
- target.c_str(),
- NULL
- };
-
- // discard stderr, no pty, stderr_fd = -1, use the default locale
- zypp::ExternalProgram prog2(argv2, zypp::ExternalProgram::Discard_Stderr, false, -1, true);
-
- int code2 = prog2.close();
-
- if (code2)
- {
- // error message
- _last_error.setLastError(msg + _("Copying failed"));
- y2error("Cannot copy /var/cache/zypp to %s", d.c_str());
- }
-
- return YCPBoolean(!code2);
-}
-
-/****************************************************************************************
- * @builtin SourceScan
- * @short Scan a Source Media
- * @description
- * Load all InstSrces found at media_url, i.e. all sources mentioned in /media.1/products.
- * If no /media.1/products is available, InstSrc is expected to be located directly
- * below media_url (product_dir: /).
- *
- * If a product_dir is provided, only the InstSrc located at media_url/product_dir is loaded.
- *
- * In contrary to @ref SourceCreate, InstSrces are loaded into the InstSrcManager,
- * but not enabled (packages and selections are not provided to the PackageManager),
- * and the SrcIds of <b>all</b> InstSrces found are returned.
- *
- * @param string url The media to scan.
- * @optarg string product_dir Restrict scan to a certain InstSrc located in media_url/product_dir.
- *
- * @return list<integer> list of SrcIds (integer).
- **/
-YCPValue
-PkgModuleFunctions::SourceScan (const YCPString& media, const YCPString& pd)
-{
- zypp::Url url;
-
- try {
- url = zypp::Url(media->value ());
- }
- catch(const zypp::Exception & expt )
- {
- y2error ("Invalid URL: %s", expt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(expt));
- return YCPList();
- }
-
- zypp::Pathname pn(pd->value ());
-
- YCPList ids;
- std::vector<zypp::RepoInfo>::size_type id;
-
- if ( pd->value().empty() ) {
-
- // scan all sources
- zypp::MediaProductSet products;
-
- try
- {
- y2milestone("Scanning products in %s ...", url.asString().c_str());
- ScanProductsWithCallBacks(url);
- products = available_products;
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("Scanning products for '%s' has failed"
- , url.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- return ids;
- }
-
- if( products.empty() )
- {
- // no products found, use the base URL instead
- zypp::MediaProductEntry entry;
- products.insert(entry);
- }
-
- for( zypp::MediaProductSet::const_iterator it = products.begin();
- it != products.end() ; ++it )
- {
- try
- {
- y2milestone("Using product %s in directory %s", it->_name.c_str(), it->_dir.c_str());
- id = createManagedSource(url, it->_dir, false, "", it->_name);
- ids->add( YCPInteger(id) );
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("SourceScan for '%s' product '%s' has failed"
- , url.asString().c_str(), pn.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- }
- }
- } else {
- y2debug("Creating source...");
-
- try
- {
- id = createManagedSource(url, pn, false, "", "");
- ids->add( YCPInteger(id) );
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("SourceScan for '%s' product '%s' has failed"
- , url.asString().c_str(), pn.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- }
- }
-
- y2milestone("Found sources: %s", ids->toString().c_str() );
-
- return ids;
-}
-
-/****************************************************************************************
- * @builtin SourceCreate
- *
- * @short Create a Source
- * @description
- * Load and enable all InstSrces found at media_url, i.e. all sources mentioned in /media.1/products.
- * If no /media.1/products is available, InstSrc is expected to be located directly below
- * media_url (product_dir: /).
- *
- * If a product_dir is provided, only the InstSrc located at media_url/product_dir is loaded
- * and enabled.
- *
- * @param string url The media to scan.
- * @optarg string product_dir Restrict scan to a certain InstSrc located in media_url/product_dir.
- *
- * @return integer The source_id of the first InstSrc found on the media.
- **/
-YCPValue
-PkgModuleFunctions::SourceCreate (const YCPString& media, const YCPString& pd)
-{
- // not base product, autoprobe source type
- return SourceCreateEx (media, pd, false, YCPString(""));
-}
-
-YCPValue
-PkgModuleFunctions::SourceCreateBase (const YCPString& media, const YCPString& pd)
-{
- // base product, autoprobe source type
- return SourceCreateEx (media, pd, true, YCPString(""));
-}
-
-/**
- * @builtin SourceCreateType
- * @short Create source of required type
- * @description
- * Create a source without autoprobing the source type. This builtin should be used only for "Plaindir" sources, because Plaindir sources are not automatically probed in SourceCreate() builtin.
- * @param media URL of the source
- * @param pd product directory (if empty the products will be searched)
- * @param type type of the source ("YaST", "YUM" or "Plaindir")
-*/
-
-YCPValue
-PkgModuleFunctions::SourceCreateType (const YCPString& media, const YCPString& pd, const YCPString& type)
-{
- // not base product, autoprobe source type
- return SourceCreateEx (media, pd, false, type);
-}
-
-YCPValue
-PkgModuleFunctions::SourceCreateEx (const YCPString& media, const YCPString& pd, bool base, const YCPString& source_type)
-{
- y2debug("Creating source...");
-
- zypp::Pathname pn(pd->value ());
-
- zypp::Url url;
-
- try {
- url = zypp::Url(media->value ());
- }
- catch(const zypp::Exception & expt )
- {
- y2error ("Invalid URL: %s", expt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(expt));
- return YCPInteger (-1LL);
- }
-
-
- YCPList ids;
- std::vector<zypp::RepoInfo>::size_type ret = -1;
-
- const std::string type = source_type->value();
-
- if ( pd->value().empty() ) {
- // scan all sources
- zypp::MediaProductSet products;
-
- try {
- ScanProductsWithCallBacks(url);
- products = available_products;
- }
- catch ( const zypp::Exception& excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error( "Cannot read the product list from the media" );
- return YCPInteger(-1LL);
- }
-
- if( products.empty() )
- {
- // no products found, use the base URL instead
- zypp::MediaProductEntry entry ;
- products.insert( entry );
- }
-
- for( zypp::MediaProductSet::const_iterator it = products.begin();
- it != products.end() ; ++it )
- {
- try
- {
- std::vector<zypp::RepoInfo>::size_type id = createManagedSource(url, it->_dir, base, type, it->_name);
- YRepo_Ptr repo = logFindRepository(id);
-
- LoadResolvablesFrom(repo->repoInfo());
-
- // return the id of the first product
- if ( it == products.begin() )
- ret = id;
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("SourceCreate for '%s' product '%s' has failed"
- , url.asString().c_str(), pn.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- return YCPInteger(-1LL);
- }
- }
- } else {
- y2debug("Creating source...");
-
- try
- {
- ret = createManagedSource(url, pn, base, type, "");
-
- YRepo_Ptr repo = logFindRepository(ret);
- repo->repoInfo().setEnabled(true);
-
- LoadResolvablesFrom(repo->repoInfo());
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("SourceCreate for '%s' product '%s' has failed"
- , url.asString().c_str(), pn.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- }
- }
-
- PkgFreshen();
- return YCPInteger(repos.size() - 1);
-}
-
-
-/****************************************************************************************
- * @builtin SourceSetEnabled
- *
- * @short Set the default activation state of an InsrSrc.
- * @param integer SrcId Specifies the InstSrc.
- * @param boolean enabled Default activation state of source.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceSetEnabled (const YCPInteger& id, const YCPBoolean& e)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- // no change required
- bool enable = e->value();
- if ((enable && repo->repoInfo().enabled())
- || (!enable && !repo->repoInfo().enabled()))
- return YCPBoolean(true);
-
- bool success = true;
-
- try
- {
- repo->repoInfo().setEnabled(enable);
-
- // add/remove resolvables
- if (enable)
- {
- // load resolvables only when they are missing
- if (!AnyResolvableFrom(repo->repoInfo().alias()))
- {
- success = LoadResolvablesFrom(repo->repoInfo());
- }
- }
- else
- {
- // the source has been disabled, remove resolvables from the pool
- RemoveResolvablesFrom(repo->repoInfo().alias());
- }
-
- PkgFreshen();
- }
- catch (const zypp::Exception& excpt)
- {
- std::string alias = repo->repoInfo().alias();
- y2error ("Error for '%s': %s", alias.c_str(), excpt.asString().c_str());
- _last_error.setLastError(alias + ": " + ExceptionAsString(excpt));
- success = false;
- }
-
- return YCPBoolean(success);
-}
-
-/****************************************************************************************
- * @builtin SourceSetAutorefresh
- *
- * @short Set whether this source should automaticaly refresh it's
- * meta data when it gets enabled. (default true, if not CD/DVD)
- * @param integer SrcId Specifies the InstSrc.
- * @param boolean enabled Whether autorefresh should be turned on or off.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceSetAutorefresh (const YCPInteger& id, const YCPBoolean& e)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- repo->repoInfo().setAutorefresh(e->value());
-
- return YCPBoolean( true );
-}
-
-/****************************************************************************************
- * @builtin SourceFinish
- * @short Disable an Installation Source
- * @param integer SrcId Specifies the InstSrc.
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceFinish (const YCPInteger& id)
-{
- return SourceSetEnabled(id, false);
-}
-
-/****************************************************************************************
- * @builtin SourceRefreshNow
- * @short Attempt to immediately refresh a Source
- * @description
- * The InsrSrc will be encouraged to check and refresh all metadata
- * cached on disk.
- *
- * @param integer SrcId Specifies the InstSrc.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceRefreshNow (const YCPInteger& id)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- try
- {
- zypp::RepoManager repomanager = CreateRepoManager();
- y2milestone("Refreshing metadata '%s'", repo->repoInfo().alias().c_str());
- RefreshWithCallbacks(repo->repoInfo());
-
- y2milestone("Caching source '%s'...", repo->repoInfo().alias().c_str());
- repomanager.buildCache(repo->repoInfo());
- }
- catch ( const zypp::Exception & expt )
- {
- y2error ("Error while refreshing the source: %s", expt.asString().c_str());
- _last_error.setLastError(repo->repoInfo().alias() + ": " + ExceptionAsString(expt));
- return YCPBoolean(false);
- }
-
- return YCPBoolean( true );
-}
-
-/****************************************************************************************
- * @builtin SourceDelete
- * @short Delete a Source
- * @description
- * Delete an InsrSrc. The InsrSrc together with all metadata cached on disk
- * is removed. The SrcId passed becomes invalid (other SrcIds stay valid).
- *
- * @param integer SrcId Specifies the InstSrc.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceDelete (const YCPInteger& id)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- bool success = true;
-
- try
- {
- // the resolvables cannot be used anymore, remove them
- RemoveResolvablesFrom(repo->repoInfo().alias());
-
- // update 'repos'
- repo->setDeleted();
-
- PkgFreshen();
- }
- catch (const zypp::Exception& excpt)
- {
- std::string alias = repo->repoInfo().alias();
- y2error ("Error for '%s': %s", alias.c_str(), excpt.asString().c_str());
- _last_error.setLastError(alias + ": " + ExceptionAsString(excpt));
- success = false;
- }
-
- return YCPBoolean(success);
-}
-
-/****************************************************************************************
- * @builtin SourceEditGet
- *
- * @short Get state of Sources
- * @description
- * Return a list of states for all known InstSources sorted according to the
- * source priority (highest first). A source state is a map:
- * $[
- * "SrcId" : YCPInteger,
- * "enabled" : YCPBoolean
- * "autorefresh": YCPBoolean
- * ];
- *
- * @return list<map> list of source states (map)
- **/
-YCPValue
-PkgModuleFunctions::SourceEditGet ()
-{
- YCPList ret;
-
- unsigned long index = 0;
- for( std::vector<YRepo_Ptr>::const_iterator it = repos.begin(); it != repos.end(); ++it, ++index)
- {
- if (!(*it)->isDeleted())
- {
- YCPMap src_map;
-
- src_map->add(YCPString("SrcId"), YCPInteger(index));
- // Note: enabled() is tribool
- src_map->add(YCPString("enabled"), YCPBoolean((*it)->repoInfo().enabled()));
- // Note: autorefresh() is tribool
- src_map->add(YCPString("autorefresh"), YCPBoolean((*it)->repoInfo().autorefresh()));
- src_map->add(YCPString("name"), YCPString((*it)->repoInfo().name()));
-
- ret->add(src_map);
- }
- }
-
- return ret;
-}
-
-/****************************************************************************************
- * @builtin SourceEditSet
- *
- * @short Configure properties of installation sources
- * @description
- * Set states of installation sources. Note: Enabling/disabling a source does not
- * (un)load the packages from the source! Use SourceSetEnabled() if you need to refresh
- * the packages in the pool.
- *
- * @param list source_states List of source states. Same format as returned by
- * @see SourceEditGet.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceEditSet (const YCPList& states)
-{
- bool error = false;
-
- for (int index = 0; index < states->size(); index++ )
- {
- if( ! states->value(index)->isMap() )
- {
- ycperror( "Pkg::SourceEditSet, entry not a map at index %d", index);
- error = true;
- continue;
- }
-
- YCPMap descr = states->value(index)->asMap();
-
- if (descr->value( YCPString("SrcId") ).isNull() || !descr->value(YCPString("SrcId"))->isInteger())
- {
- ycperror( "Pkg::SourceEditSet, SrcId not defined for a source description at index %d", index);
- error = true;
- continue;
- }
-
- std::vector<YRepo_Ptr>::size_type id = descr->value( YCPString("SrcId") )->asInteger()->value();
-
- YRepo_Ptr repo = logFindRepository(id);
- if (!repo)
- {
- ycperror( "Pkg::SourceEditSet, source %d not found", index);
- error = true;
- continue;
- }
-
- // now, we have the source
- if( ! descr->value( YCPString("enabled")).isNull() && descr->value(YCPString("enabled"))->isBoolean ())
- {
- bool enable = descr->value(YCPString("enabled"))->asBoolean ()->value();
-
- if (repo->repoInfo().enabled() != enable)
- {
- ycpwarning("Pkg::SourceEditSet() does not refresh the pool (src: %zd, state: %s)", id, enable ? "disabled -> enabled" : "enabled -> disabled");
- }
-
- y2debug("set enabled: %d", enable);
- repo->repoInfo().setEnabled(enable);
- }
-
- if( !descr->value(YCPString("autorefresh")).isNull() && descr->value(YCPString("autorefresh"))->isBoolean ())
- {
- bool autorefresh = descr->value(YCPString("autorefresh"))->asBoolean()->value();
- y2debug("set autorefresh: %d", autorefresh);
- repo->repoInfo().setAutorefresh( autorefresh );
- }
-
- if( !descr->value(YCPString("name")).isNull() && descr->value(YCPString("name"))->isString())
- {
- // rename the source
- y2debug("set name: %s", descr->value(YCPString("name"))->asString()->value().c_str());
- repo->repoInfo().setName(descr->value(YCPString("name"))->asString()->value());
- }
-
-#warning SourceEditSet ordering not implemented yet
- }
-
- PkgFreshen();
- return YCPBoolean( !error );
-}
-
-/////////////////////////////////////////////////////////////////////////////////////////
-//
-// DEPRECATED
-//
-/////////////////////////////////////////////////////////////////////////////////////////
-
-/****************************************************************************************
- * Pkg::SourceRaisePriority (integer SrcId) -> bool
+/* ------------------------------------------------------------------------------
+ * Copyright (c) 2007 Novell, Inc. All Rights Reserved.
*
- * Raise priority of source.
*
- * @param SrcId Specifies the InstSrc.
+ * This program is free software; you can redistribute it and/or modify it under
+ * the terms of version 2 of the GNU General Public License as published by the
+ * Free Software Foundation.
*
- * @return bool
- **/
-YCPValue
-PkgModuleFunctions::SourceRaisePriority (const YCPInteger& id)
-{
-#warning SourceRaisePriority is not implemented
- y2warning("SourceRaisePriority is NOT implemented");
-/* zypp::Source_Ref src;
-
- try {
- src = logFindRepository(id->value());
- }
- catch (const zypp::Exception& excpt)
- {
- return YCPBoolean(false);
- }
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+ * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along with
+ * this program; if not, contact Novell, Inc.
+ *
+ * To contact Novell about this file by physical or electronic mail, you may find
+ * current contact information at www.novell.com.
+ * ------------------------------------------------------------------------------
+ */
- // raise priority by one
- src.setPriority(src.priority() + 1);
+/*
+ File: $Id:$
+ Author: Ladislav Slezák <lslezak(a)novell.com>
+ Summary: Functions for saving repository configuration
*/
- return YCPBoolean( true );
+#include <Callbacks.h>
+#include <Callbacks.YCP.h>
+
+#include <PkgModule.h>
+#include <PkgModuleFunctions.h>
-}
/****************************************************************************************
- * Pkg::SourceLowerPriority (integer SrcId) -> void
- *
- * Lower priority of source.
- *
- * @param SrcId Specifies the InstSrc.
+ * @builtin SourceReleaseAll
*
- * @return bool
- */
+ * @short Release all medias hold by all sources
+ * @return boolean
+ **/
YCPValue
-PkgModuleFunctions::SourceLowerPriority (const YCPInteger& id)
+PkgModuleFunctions::SourceReleaseAll ()
{
-#warning SourceLowerPriority is not implemented
- y2warning("SourceLowerPriority is NOT implemented");
-/*
- zypp::Source_Ref src;
+ y2milestone("Releasing all sources...");
+ bool ret = true;
- try {
- src = logFindRepository(id->value());
- }
- catch (const zypp::Exception& excpt)
+ for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
+ it != repos.end(); ++it)
{
- return YCPBoolean(false);
+ try
+ {
+ (*it)->mediaAccess()->release();
+ }
+ catch (const zypp::media::MediaException & ex)
+ {
+ y2warning("Failed to release media for repo: %s", ex.msg().c_str());
+ ret = false;
+ }
}
- // lower priority by one
- src.setPriority(src.priority() - 1);
-*/
- return YCPBoolean( true );
+ return YCPBoolean(ret);
}
-/****************************************************************************************
- * Pkg::SourceSaveRanks () -> boolean
+/******************************************************************************
+ * @builtin SourceSaveAll
*
- * @short Obsoleted function, do not use
- * @return boolean true
+ * @short Save all InstSrces.
+ * @return boolean
**/
YCPValue
-PkgModuleFunctions::SourceSaveRanks ()
+PkgModuleFunctions::SourceSaveAll ()
{
- y2error( "SourceSaveRanks not implemented" );
+ y2milestone("Saving the source setup...");
- return YCPBoolean( true );
-}
+ zypp::RepoManager repomanager = CreateRepoManager();
-/****************************************************************************************
- * @builtin SourceMoveDownloadArea
- *
- * @short Move download area of CURL-based sources to specified directory
- * @param path specifies the path to move the download area to
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceMoveDownloadArea (const YCPString & path)
-{
- try
- {
- y2milestone("Moving download area of all sources to %s", path->value().c_str());
- zypp::media::MediaManager manager;
- manager.setAttachPrefix(path->value());
- }
- catch (zypp::Exception & excpt)
+ // remove deleted repos (the old configurations) at first
+ for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
+ it != repos.end(); ++it)
{
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error("Pkg::SourceMoveDownloadArea has failed: %s", excpt.msg().c_str());
- return YCPBoolean(false);
- }
+ // the repo has been removed
+ if ((*it)->isDeleted())
+ {
+ std::string repo_alias = (*it)->repoInfo().alias();
- y2milestone( "Download areas moved");
+ try
+ {
+ // remove the metadata
+ zypp::RepoStatus raw_metadata_status = repomanager.metadataStatus((*it)->repoInfo());
+ if (!raw_metadata_status.empty())
+ {
+ y2milestone("Removing metadata for source '%s'...", repo_alias.c_str());
+ repomanager.cleanMetadata((*it)->repoInfo());
+ }
- return YCPBoolean(true);
-}
+ // remove the cache
+ if (repomanager.isCached((*it)->repoInfo()))
+ {
+ y2milestone("Removing cache for '%s'...", repo_alias.c_str());
+ repomanager.cleanCache((*it)->repoInfo());
+ }
-/*
- * A helper function - remove all resolvables from the repository from the pool
- */
-void PkgModuleFunctions::RemoveResolvablesFrom(const std::string &alias)
-{
- // remove the resolvables if they have been loaded
- // FIXME: can be implemented better? we need a ResStore object for removing,
- // which means search for a resolvable in the pool and get the Repository
- // object which can be asked for all resolvables in it
- for (zypp::ResPool::const_iterator it = zypp_ptr()->pool().begin()
- ; it != zypp_ptr()->pool().end()
- ; ++it)
- {
- if (it->resolvable()->repository().info().alias() == alias)
- {
- y2milestone("Removing all resolvables from '%s' from the pool...", alias.c_str());
- zypp_ptr()->removeResolvables(it->resolvable()->repository().resolvables());
- break;
+ repomanager.getRepositoryInfo(repo_alias);
+ y2milestone("Removing repository '%s'", repo_alias.c_str());
+ repomanager.removeRepository((*it)->repoInfo());
+ }
+ catch (const zypp::repo::RepoNotFoundException &ex)
+ {
+ // repository not found -- not critical, continue
+ y2warning("No such repository: %s", repo_alias.c_str());
+ }
+ catch (const zypp::Exception & excpt)
+ {
+ y2error("Pkg::SourceSaveAll has failed: %s", excpt.msg().c_str() );
+ _last_error.setLastError(ExceptionAsString(excpt));
+ return YCPBoolean(false);
+ }
}
}
-}
-/*
- * A helper function - is there any resolvable from the repository in the pool?
- */
-bool PkgModuleFunctions::AnyResolvableFrom(const std::string &alias)
-{
- for (zypp::ResPool::const_iterator it = zypp_ptr()->pool().begin()
- ; it != zypp_ptr()->pool().end()
- ; ++it)
+ // save all repos (the current configuration)
+ for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
+ it != repos.end(); ++it)
{
- if (it->resolvable()->repository().info().alias() == alias)
+ if (!(*it)->isDeleted())
{
- return true;
- }
- }
-
- return false;
-}
-
-/*
- * A helper function - load resolvable from the repository into the pool
- * Warning: Use AnyResolvableFrom() method for checing if the resolvables might be already loaded
- */
-bool PkgModuleFunctions::LoadResolvablesFrom(const zypp::RepoInfo &repoinfo)
-{
- bool success = true;
- unsigned int size_start = zypp_ptr()->pool().size();
- y2milestone("Loading resolvables from '%s', pool size at start: %d", repoinfo.alias().c_str(), size_start);
-
- try
- {
- zypp::RepoManager repomanager = CreateRepoManager();
+ std::string current_alias = (*it)->repoInfo().alias();
- // build cache if needed
- if (!repomanager.isCached(repoinfo))
- {
- zypp::RepoStatus raw_metadata_status = repomanager.metadataStatus(repoinfo);
- if (raw_metadata_status.empty())
+ try
{
- y2milestone("Missing metadata for source '%s', downloading...", repoinfo.alias().c_str());
- RefreshWithCallbacks(repoinfo);
+ try
+ {
+ // if the repository already exists then just modify it
+ repomanager.getRepositoryInfo(current_alias);
+ y2milestone("Modifying repository '%s'", current_alias.c_str());
+ repomanager.modifyRepository(current_alias, (*it)->repoInfo());
+ }
+ catch (const zypp::repo::RepoNotFoundException &ex)
+ {
+ // the repository was not found, add it
+ y2milestone("Adding repository '%s'", current_alias.c_str());
+ repomanager.addRepository((*it)->repoInfo());
+ }
+ }
+ catch (zypp::Exception & excpt)
+ {
+ y2error("Pkg::SourceSaveAll has failed: %s", excpt.msg().c_str() );
+ _last_error.setLastError(ExceptionAsString(excpt));
+ return YCPBoolean(false);
}
-
- y2milestone("Caching source '%s'...", repoinfo.alias().c_str());
- repomanager.buildCache(repoinfo);
}
-
- zypp::Repository repository = repomanager.createFromCache(repoinfo);
- const zypp::ResStore &store = repository.resolvables();
-
- // load resolvables
- zypp_ptr()->addResolvables(store);
-
- y2milestone("Loaded %zd resolvables", store.size());
- }
- catch(const zypp::repo::RepoNotCachedException &excpt )
- {
- std::string alias = repoinfo.alias();
- y2error ("Resolvables from '%s' havn't been loaded: %s", alias.c_str(), excpt.asString().c_str());
- _last_error.setLastError("'" + alias + "': " + ExceptionAsString(excpt));
- success = false;
-
- // FIXME ??
- /*
- // disable the source
- y2error("Disabling source %s", url.c_str());
- repo->disable();
- */
- }
- catch (const zypp::Exception& excpt)
- {
- std::string alias = repoinfo.alias();
- y2internal("Error: Loading resolvables failed: %s", ExceptionAsString(excpt).c_str());
- _last_error.setLastError("'" + alias + "': " + ExceptionAsString(excpt));
- success = false;
}
- unsigned int size_end = zypp_ptr()->pool().size();
- y2milestone("Pool size at end: %d (loaded %d resolvables)", size_end, size_end - size_start);
- return success;
+ y2milestone("All sources have been saved");
+
+ return YCPBoolean(true);
}
/****************************************************************************************
- * @builtin RepositoryProbe
+ * @builtin SourceFinishAll
*
- * @short Probe type of the repository
- * @param url specifies the path to the repository
- * @param prod_dir product directory (if empty the url is probed directly)
- * @return string repository type ("NONE" if type could be determined, nil if an error occurred (e.g. resolving the hostname)
+ * @short Save and then disable all InstSrces.
+ * @description
+ * If there are no enabled sources, do nothing
+ * (idempotence hack, broken design: #155459, #176013, use SourceSaveAll).
+ * @return boolean
**/
-YCPValue PkgModuleFunctions::RepositoryProbe(const YCPString& url, const YCPString& prod_dir)
+YCPValue
+PkgModuleFunctions::SourceFinishAll ()
{
- y2milestone("Probing repository type: '%s'...", url->value().c_str());
- zypp::RepoManager repomanager = CreateRepoManager();
- std::string ret;
-
try
{
- zypp::Url probe_url(url->value());
-
- // add the product directory
- std::string prod = prod_dir->value();
-
- if (!prod.empty())
+ bool found_enabled = false;
+ for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
+ it != repos.end(); ++it)
{
- // add "/" at the begining if it's missing
- if (std::string(prod, 0, 1) != "/")
+ if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
{
- prod = "/" + prod;
+ found_enabled = true;
+ break;
}
-
- // merge the URL path and the product path
- std::string path = probe_url.getPathName();
- path += prod;
-
- y2milestone("Using probing path: %s", path.c_str());
- probe_url.setPathName(path);
}
- // add "ro" mount option
- probe_url = addRO(probe_url);
-
- // autoprobe type of the repository
- zypp::repo::RepoType repotype = ProbeWithCallbacks(probe_url);
-
- ret = zypp2yastType(repotype.asString());
- y2milestone("Detected type: '%s'...", ret.c_str());
- }
- catch (const zypp::Exception& excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error( "Cannot detect the repository type" );
- return YCPVoid();
- }
-
- return YCPString(ret);
-}
-
-/****************************************************************************************
- * @builtin RepositoryScan
- *
- * @short Scan available products in the repository
- * @param url specifies the path to the repository
- * @return list<list<string>> list of the products: [ [ <product_name_1> <directory_1> ], ...]
- **/
-YCPValue PkgModuleFunctions::RepositoryScan(const YCPString& url)
-{
- zypp::MediaProductSet products;
-
- try
- {
- zypp::Url baseurl(url->value());
+ if (!found_enabled)
+ {
+ y2milestone( "No enabled sources, skipping SourceFinishAll()" );
+ return YCPBoolean( true );
+ }
- baseurl = addRO(baseurl);
+ SourceSaveAll();
- ScanProductsWithCallBacks(baseurl);
- products = available_products;
+ y2milestone( "Disabling all sources...") ;
+ for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
+ it != repos.end(); ++it)
+ {
+ (*it)->repoInfo().setEnabled(false);
+ }
+ // TODO FIXME remove all resolvables??
}
- catch ( const zypp::Exception& excpt)
+ catch (zypp::Exception & excpt)
{
+ y2error("Pkg::SourceFinishAll has failed: %s", excpt.msg().c_str() );
_last_error.setLastError(ExceptionAsString(excpt));
- y2error( "Cannot read the product list from the media" );
- return YCPList();
- }
-
- YCPList ret;
-
- for( zypp::MediaProductSet::const_iterator it = products.begin();
- it != products.end() ; ++it )
- {
- YCPList prod;
-
- // add product directory
- prod.add(YCPString(it->_name));
- // add product name
- prod.add(YCPString(it->_dir.asString()));
-
- ret.add(prod);
+ return YCPBoolean(false);
}
- y2milestone("Found products: %s", ret->toString().c_str());
+ y2milestone("All sources have been saved and disabled");
- return ret;
+ return YCPBoolean(true);
}
-// convert libzypp type to yast strings ("YaST", "YUM" or "Plaindir")
-std::string PkgModuleFunctions::zypp2yastType(const std::string &type)
-{
- std::string ret(type);
-
- if (type_conversion_table.empty())
- {
- // initialize the conversion map
- type_conversion_table["rpm-md"] = "YUM";
- type_conversion_table["yast2"] = "YaST";
- type_conversion_table["plaindir"] = "Plaindir";
- type_conversion_table["NONE"] = "NONE";
- }
-
- std::map<std::string,std::string>::const_iterator it = type_conversion_table.find(type);
- // found in the conversion table
- if (it != type_conversion_table.end())
- {
- ret = it->second;
- }
- else
- {
- y2error("Cannot convert type '%s'", type.c_str());
- }
-
- return ret;
-}
-
-std::string PkgModuleFunctions::yast2zyppType(const std::string &type)
+/****************************************************************************************
+ * @builtin SourceFinish
+ * @short Disable an Installation Source
+ * @param integer SrcId Specifies the InstSrc.
+ * @return boolean
+ **/
+YCPValue
+PkgModuleFunctions::SourceFinish (const YCPInteger& id)
{
- // do conversion from the Yast type ("YaST", "YUM", "Plaindir")
- // to libzypp type ("yast", "yum", "plaindir")
- // we can simply use toLower instead of a conversion table
- // in this case
- return zypp::str::toLower(type);
+ return SourceSetEnabled(id, false);
}
Copied: trunk/pkg-bindings/src/Source_Set.cc (from r42708, trunk/pkg-bindings/src/Source.cc)
URL: http://svn.opensuse.org/viewcvs/yast/trunk/pkg-bindings/src/Source_Set.cc?p…
==============================================================================
--- trunk/pkg-bindings/src/Source.cc (original)
+++ trunk/pkg-bindings/src/Source_Set.cc Thu Dec 6 07:56:58 2007
@@ -1,2451 +1,78 @@
-/*---------------------------------------------------------------------\
-| |
-| __ __ ____ _____ ____ |
-| \ \ / /_ _/ ___|_ _|___ \ |
-| \ V / _` \___ \ | | __) | |
-| | | (_| |___) || | / __/ |
-| |_|\__,_|____/ |_| |_____| |
-| |
-| core system |
-| (C) SuSE GmbH |
-\----------------------------------------------------------------------/
-
- File: PkgModuleFunctionsSource.cc
-
- Author: Klaus Kaempf <kkaempf(a)suse.de>
- Maintainer: Klaus Kaempf <kkaempf(a)suse.de>
-
- Summary: Access to Installation Sources
- Namespace: Pkg
- Purpose: Access to InstSrc
- Handles source related Pkg::function (list_of_arguments) calls
- from WFMInterpreter.
-/-*/
-//#include <unistd.h>
-//#include <sys/statvfs.h>
-
-#include <iostream>
-
-#include <ycpTools.h>
-#include <PkgModule.h>
-#include <PkgModuleFunctions.h>
-
-#include <Callbacks.h>
-#include <Callbacks.YCP.h>
-
-#include <zypp/Product.h>
-#include <zypp/media/MediaManager.h>
-#include <zypp/media/Mount.h>
-#include <zypp/Pathname.h>
-
-#include <zypp/RepoInfo.h>
-#include <zypp/RepoManager.h>
-#include <zypp/Fetcher.h>
-#include <zypp/repo/RepoType.h>
-#include <zypp/MediaProducts.h>
-#include <zypp/ExternalProgram.h>
-#include <zypp/ProgressData.h>
-
-#include <sstream> // ostringstream
-
-#include <PkgProgress.h>
-
-/*
- Textdomain "pkg-bindings"
-*/
-
-// scanned available products
-// hack: zypp/MediaProducts.h cannot be included in PkgModuleFunctions.h
-zypp::MediaProductSet available_products;
-
-// this method should be used instead of zypp::productsInMedia()
-// it initializes the download callbacks
-void PkgModuleFunctions::ScanProductsWithCallBacks(const zypp::Url &url)
-{
- CallInitDownload(std::string(_("Scanning products in ") + url.asString()));
-
- extern ZyppRecipients::MediaChangeSensitivity _silent_probing;
- // remember the current value
- ZyppRecipients::MediaChangeSensitivity _silent_probing_old = _silent_probing;
-
- // disable media change callback for optional file
- _silent_probing = ZyppRecipients::MEDIA_CHANGE_DISABLE;
-
- y2milestone("Scanning products in %s ...", url.asString().c_str());
-
- try
- {
- available_products.clear();
- zypp::productsInMedia(url, available_products);
- }
- catch(...)
- {
- // call the final event even in case of exception
- CallDestDownload();
-
- // restore the probing flag
- _silent_probing = _silent_probing_old;
-
- // rethrow the execption
- throw;
- }
-
- CallDestDownload();
-
- // restore the probing flag
- _silent_probing = _silent_probing_old;
-}
-
-void PkgModuleFunctions::CallSourceReportStart(const std::string &text)
-{
- // get the YCP callback handler
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_SourceReportStart);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- // add parameters
- ycp_handler->appendParameter( YCPInteger(0LL) );
- ycp_handler->appendParameter( YCPString("") );
- ycp_handler->appendParameter( YCPString(text) );
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-
-void PkgModuleFunctions::CallSourceReportEnd(const std::string &text)
-{
- // get the YCP callback handler for end event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_SourceReportEnd);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- // add parameters
- ycp_handler->appendParameter( YCPInteger(0LL) );
- ycp_handler->appendParameter( YCPString("") );
- ycp_handler->appendParameter( YCPString(text) );
- ycp_handler->appendParameter( YCPString("NO_ERROR") );
- ycp_handler->appendParameter( YCPString("") );
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-
-void PkgModuleFunctions::CallSourceReportInit()
-{
- // get the YCP callback handler for init event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_SourceReportInit);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-
-void PkgModuleFunctions::CallSourceReportDestroy()
-{
- // get the YCP callback handler for destroy event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_SourceReportDestroy);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-
-void PkgModuleFunctions::CallInitDownload(const std::string &task)
-{
- // get the YCP callback handler for destroy event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_InitDownload);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- ycp_handler->appendParameter(YCPString(task));
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-
-void PkgModuleFunctions::CallDestDownload()
-{
- // get the YCP callback handler for destroy event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_DestDownload);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-}
-
-// this method should be used instead of RepoManager::refreshMetadata()
-void PkgModuleFunctions::RefreshWithCallbacks(const zypp::RepoInfo &repo)
-{
- CallInitDownload(std::string(_("Refreshing repository ") + repo.alias()));
-
- try
- {
- zypp::RepoManager repomanager = CreateRepoManager();
- repomanager.refreshMetadata(repo);
- }
- catch(...)
- {
- // call the final event even in case of exception
- CallDestDownload();
- // rethrow the execption
- throw;
- }
-
- CallDestDownload();
-}
-
-// this method should be used instead of RepoManager::probe()
-zypp::repo::RepoType PkgModuleFunctions::ProbeWithCallbacks(const zypp::Url &url)
-{
- CallInitDownload(std::string(_("Probing repository ") + url.asString()));
-
- zypp::repo::RepoType repotype;
-
- extern ZyppRecipients::MediaChangeSensitivity _silent_probing;
- // remember the current value
- ZyppRecipients::MediaChangeSensitivity _silent_probing_old = _silent_probing;
-
- // disable media change callback for optional file
- _silent_probing = ZyppRecipients::MEDIA_CHANGE_DISABLE;
-
- try
- {
- // probe type of the repository
- zypp::RepoManager repomanager = CreateRepoManager();
- repotype = repomanager.probe(url);
- }
- catch(...)
- {
- // call the final event even in case of exception
- CallDestDownload();
-
- // restore the probing flag
- _silent_probing = _silent_probing_old;
-
- // rethrow the execption
- throw;
- }
-
- CallDestDownload();
-
- // restore the probing flag
- _silent_probing = _silent_probing_old;
-
- return repotype;
-}
-
-/**
- * Logging helper:
- * call zypp::SourceManager::sourceManager()->findSource
- * and in case of exception, log error and setLastError AND RETHROW
- */
-YRepo_Ptr PkgModuleFunctions::logFindRepository(std::vector<YRepo_Ptr>::size_type id)
-{
- try
- {
- if (id < 0 || id >= repos.size())
- {
- // not found
- throw(std::exception());
- }
-
- if (!repos[id])
- {
- // not found
- throw(std::exception());
- }
-
- if (repos[id]->isDeleted())
- {
- y2error("Source %zd has been deleted, the ID is not valid", id);
- return YRepo_Ptr();
- }
-
- return repos[id];
- }
- catch (...)
- {
- y2error("Cannot find source with ID: %zd", id);
- // TODO: improve the error message
- _last_error.setLastError(_("Cannot find source"));
- }
-
- // not found, return empty pointer
- return YRepo_Ptr();
-}
-
-long long PkgModuleFunctions::logFindAlias(const std::string &alias) const
-{
- std::vector<YRepo_Ptr>::size_type index = 0;
-
- for(std::vector<YRepo_Ptr>::const_iterator it = repos.begin(); it != repos.end() ; ++it, ++index)
- {
- if (!(*it)->isDeleted() && (*it)->repoInfo().alias() == alias)
- return index;
- }
-
- return -1LL;
-}
-
-bool PkgModuleFunctions::aliasExists(const std::string &alias) const
-{
- for(std::vector<YRepo_Ptr>::const_iterator it = repos.begin(); it != repos.end() ; ++it)
- {
- if (!(*it)->isDeleted() && (*it)->repoInfo().alias() == alias)
- return true;
- }
-
- return false;
-}
-
-/****************************************************************************************
- * @builtin SourceSetRamCache
- * @short Obsoleted function, do not use
- * @param boolean
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceSetRamCache (const YCPBoolean& a)
-{
- y2warning( "Pkg::SourceSetRamCache is obsolete and does nothing");
- return YCPBoolean( true );
-}
-
-
-/****************************************************************************************
- * @builtin SourceRestore
- *
- * @short Restore the sources from the persistent store
- * @description
- * Make sure the Source Manager is up and knows all available installation sources.
- * It's safe to call this multiple times, and once the installation sources are
- * actually enabled, it's even cheap
- *
- * @return boolean True on success
- **/
-YCPValue
-PkgModuleFunctions::SourceRestore()
-{
- if (repos.size() > 0)
- {
- y2warning("Number of registered repositories: %zd, skipping repository load!", repos.size());
- return YCPBoolean(true);
- }
-
- bool success = true;
-
- try
- {
- zypp::RepoManager repomanager = CreateRepoManager();
- std::list<zypp::RepoInfo> reps = repomanager.knownRepositories();
-
- repos.clear();
- for (std::list<zypp::RepoInfo>::iterator it = reps.begin();
- it != reps.end(); ++it)
- {
- repos.push_back(new YRepo(*it));
- }
- }
- catch (const zypp::Exception& excpt)
- {
- // FIXME: assuming the sources are already initialized
- y2error ("Error in SourceRestore: %s", excpt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- success = false;
- }
-
- return YCPBoolean(success);
-}
-
-/****************************************************************************************
- * @builtin SourceGetBrokenSources
- *
- * @short Return list of broken sources (sources which failed to restore)
- * @description
- * Get list of all sources which could not have been restored.
- * @return list<string> list of aliases (product names or URLs)
- **/
-YCPValue PkgModuleFunctions::SourceGetBrokenSources()
-{
- y2warning("Pkg::SourceGetBrokenSources() is obsoleted, it's not needed anymore.");
- return YCPList();
-}
-
-bool PkgModuleFunctions::SourceLoadReceiver(const zypp::ProgressData &progress)
-{
- y2milestone("Source Load receiver: %lld (%lld%%)", progress.val(), progress.reportValue());
-
- // get the YCP callback handler for destroy event
- Y2Function* ycp_handler = _callbackHandler._ycpCallbacks.createCallback(CallbackHandler::YCPCallbacks::CB_ProcessProgress);
-
- // is the callback registered?
- if (ycp_handler != NULL)
- {
- ycp_handler->appendParameter(YCPInteger(progress.reportValue()));
- // evaluate the callback function
- ycp_handler->evaluateCall();
- }
-
- return true;
-}
-
-/****************************************************************************************
- * @builtin SourceLoad
- *
- * @short Load resolvables from the installation sources
- * @description
- * Refresh the pool - Add/remove resolvables from the enabled/disabled sources.
- * @return boolean True on success
- **/
-YCPValue
-PkgModuleFunctions::SourceLoad()
-{
- std::list<std::string> stages;
- stages.push_back("Refresh Sources");
- stages.push_back("Rebuild Cache");
- stages.push_back("Load Data");
-
- PkgProgress pkgprogress(_callbackHandler);
-
- // 3 steps per repository (download, cache rebuild, load resolvables)
- pkgprogress.Start("Loading the Package Manager...", stages, "help");
-
- YCPValue ret = SourceLoadImpl(pkgprogress);
-
- pkgprogress.Done();
-
- return ret;
-}
-
-
-/****************************************************************************************
- * @builtin SourceLoad
- *
- * @short Load resolvables from the installation sources
- * @description
- * Refresh the pool - Add/remove resolvables from the enabled/disabled sources.
- * @return boolean True on success
- **/
-YCPValue
-PkgModuleFunctions::SourceLoadImpl(PkgProgress &progress)
-{
- bool success = true;
-
- int repos_to_load = 0;
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
- {
- repos_to_load++;
- }
- }
-
- // set max. value (3 steps per repository - refresh, rebuild, load)
- zypp::ProgressData prog_total(repos_to_load * 3);
- prog_total.sendTo(progress.Receiver());
-
- zypp::RepoManager repomanager = CreateRepoManager();
-
- // refresh metadata
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- // load resolvables only from enabled repos which are not deleted
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
- {
- // sub tasks
- zypp::CombinedProgressData refresh_subprogress(prog_total, 1);
-
- if (AnyResolvableFrom((*it)->repoInfo().alias()))
- {
- y2milestone("Resolvables from '%s' are already present, not loading", (*it)->repoInfo().alias().c_str());
- }
- else
- {
- // autorefresh the source
- if ((*it)->repoInfo().autorefresh())
- {
- try
- {
- y2milestone("Autorefreshing source: %s", (*it)->repoInfo().alias().c_str());
- RefreshWithCallbacks((*it)->repoInfo());
-
- zypp::ProgressData prog(1);
- prog.sendTo(refresh_subprogress);
- RefreshWithCallbacks((*it)->repoInfo());
- prog.toMax();
- }
- // NOTE: subtask progresses are reported as done in the descructor
- // no need to handle them in the exception code
- catch (const zypp::Exception& excpt)
- {
- y2error ("Error in SourceLoad: %s", excpt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- success = false;
- }
- }
- }
- }
- }
-
- progress.NextStage();
-
- // rebuild cache
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- // load resolvables only from enabled repos which are not deleted
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
- {
- // sub tasks
- zypp::CombinedProgressData rebuild_subprogress(prog_total, 1);
-
- if (AnyResolvableFrom((*it)->repoInfo().alias()))
- {
- y2milestone("Resolvables from '%s' are already present, not loading", (*it)->repoInfo().alias().c_str());
- }
- else
- {
- // autorefresh the source
- if ((*it)->repoInfo().autorefresh())
- {
- try
- {
- // rebuild cache (the default policy is "if needed")
- y2milestone("Rebuilding cache for '%s'...", (*it)->repoInfo().alias().c_str());
-
- zypp::ProgressData prog(1);
- prog.sendTo(rebuild_subprogress);
- repomanager.buildCache((*it)->repoInfo());
- prog.toMax();
- }
- // NOTE: subtask progresses are reported as done in the descructor
- // no need to handle them in the exception code
- catch (const zypp::Exception& excpt)
- {
- y2error ("Error in SourceLoad: %s", excpt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- success = false;
- }
- }
- }
- }
- }
-
- progress.NextStage();
-
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- // load resolvables only from enabled repos which are not deleted
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
- {
- // sub tasks
- zypp::CombinedProgressData load_subprogress(prog_total, 1);
-
- if (AnyResolvableFrom((*it)->repoInfo().alias()))
- {
- y2milestone("Resolvables from '%s' are already present, not loading", (*it)->repoInfo().alias().c_str());
- }
- else
- {
- zypp::ProgressData prog(1);
- prog.sendTo(load_subprogress);
-
- // load objects
- success = LoadResolvablesFrom((*it)->repoInfo()) && success;
-
- prog.toMax();
- }
- }
- }
-
- // report 100%
- prog_total.toMax();
-
- return YCPBoolean(success);
-}
-
-
-/****************************************************************************************
- * @builtin SourceStartManager
- *
- * @short Start the source manager - restore the sources and load the resolvables
- * @description
- * Calls SourceRestore(), if argument enable is true SourceLoad() is called.
- * @param boolean enable If true the resolvables are loaded from the enabled sources
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceStartManager (const YCPBoolean& enable)
-{
- PkgProgress pkgprogress(_callbackHandler);
-
- // display the progress only when 'enable' is true
- if (enable->value())
- {
- std::list<std::string> stages;
- stages.push_back("Load Sources");
- stages.push_back("Refresh Sources");
- stages.push_back("Rebuild Cache");
- stages.push_back("Load Data");
-
- // 3 steps per repository (download, cache rebuild, load resolvables)
- pkgprogress.Start("Loading the Package Manager...", stages, "help");
- }
-
- YCPValue ret = SourceStartManagerImpl(enable, pkgprogress);
-
- if (enable->value())
- {
- pkgprogress.Done();
- }
-
- return ret;
-}
-
-/****************************************************************************************
- * @builtin SourceStartManager
- *
- * @short Start the source manager - restore the sources and load the resolvables
- * @description
- * Calls SourceRestore(), if argument enable is true SourceLoad() is called.
- * @param boolean enable If true the resolvables are loaded from the enabled sources
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceStartManagerImpl(const YCPBoolean& enable, PkgProgress &progress)
-{
- YCPValue success = SourceRestore();
-
- progress.NextStage();
-
- if( enable->value() )
- {
- if (!success->asBoolean()->value())
- {
- y2warning("SourceStartManager: Some sources have not been restored, loading only the active sources...");
- }
-
- // enable all sources and load the resolvables
- success = YCPBoolean(SourceLoadImpl(progress)->asBoolean()->value() && success->asBoolean()->value());
- }
-
- return success;
-}
-
-/****************************************************************************************
- * @builtin SourceStartCache
- *
- * @short Make sure the InstSrcManager is up, and return the list of SrcIds.
- * @description
- * Make sure the InstSrcManager is up, and return the list of SrcIds.
- * In fact nothing more than:
- *
- * <code>
- * SourceStartManager( enabled_only );
- * return SourceGetCurrent( enabled_only );
- * </code>
- *
- * @param boolean enabled_only If true, make sure all InstSrces are enabled according to
- * their default, and return the Ids of enabled InstSrces only. If false, return
- * the Ids of all known InstSrces.
- *
- * @return list<integer> list of SrcIds
- **/
-YCPValue
-PkgModuleFunctions::SourceStartCache (const YCPBoolean& enabled)
-{
- try
- {
- SourceStartManager(enabled);
-
- return SourceGetCurrent(enabled);
- }
- catch (const zypp::Exception& excpt)
- {
- y2error ("Error in SourceStartCache: %s", excpt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- }
- // catch an exception from boost (e.g. a file cannot be read by non-root user)
- catch (const std::exception& err)
- {
- y2error ("Error in SourceStartCache: %s", err.what());
- _last_error.setLastError(err.what());
- }
- catch (...)
- {
- y2error("Unknown error in SourceStartCache");
- }
-
- return YCPList();
-}
-
-/****************************************************************************************
- * @builtin SourceCleanupBroken
- *
- * @short Clean up all sources that were not properly restored on the last
- * call of SourceStartManager or SourceStartCache.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceCleanupBroken ()
-{
- y2warning("Pkg::SourceCleanupBroken() is obsoleted, it's not needed anymore.");
- return YCPBoolean(true);
-}
-
-/****************************************************************************************
- * @builtin SourceGetCurrent
- *
- * @short Return the list of all InstSrc Ids.
- *
- * @param boolean enabled_only If true, or omitted, return the Ids of all enabled InstSrces.
- * If false, return the Ids of all known InstSrces.
- *
- * @return list<integer> list of SrcIds (integer)
- **/
-YCPValue
-PkgModuleFunctions::SourceGetCurrent (const YCPBoolean& enabled)
-{
- YCPList res;
-
- std::vector<YRepo_Ptr>::size_type index = 0;
- for( std::vector<YRepo_Ptr>::const_iterator it = repos.begin(); it != repos.end() ; ++it, ++index )
- {
- // ignore disabled sources if requested
- if (enabled->value())
- {
- // Note: enabled() is tribool!
- if ((*it)->repoInfo().enabled())
- {
- }
- else if (!(*it)->repoInfo().enabled())
- {
- continue;
- }
- else
- {
- continue;
- }
- }
-
- // ignore deleted sources
- if ((*it)->isDeleted())
- {
- continue;
- }
-
- res->add( YCPInteger(index) );
- }
-
- return res;
-}
-
-/****************************************************************************************
- * @builtin SourceReleaseAll
- *
- * @short Release all medias hold by all sources
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceReleaseAll ()
-{
- y2milestone("Releasing all sources...");
- bool ret = true;
-
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- try
- {
- (*it)->mediaAccess()->release();
- }
- catch (const zypp::media::MediaException & ex)
- {
- y2warning("Failed to release media for repo: %s", ex.msg().c_str());
- ret = false;
- }
- }
-
- return YCPBoolean(ret);
-}
-
-/******************************************************************************
- * @builtin SourceSaveAll
- *
- * @short Save all InstSrces.
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceSaveAll ()
-{
- y2milestone("Saving the source setup...");
-
- zypp::RepoManager repomanager = CreateRepoManager();
-
- // remove deleted repos (the old configurations) at first
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- // the repo has been removed
- if ((*it)->isDeleted())
- {
- std::string repo_alias = (*it)->repoInfo().alias();
-
- try
- {
- // remove the metadata
- zypp::RepoStatus raw_metadata_status = repomanager.metadataStatus((*it)->repoInfo());
- if (!raw_metadata_status.empty())
- {
- y2milestone("Removing metadata for source '%s'...", repo_alias.c_str());
- repomanager.cleanMetadata((*it)->repoInfo());
- }
-
- // remove the cache
- if (repomanager.isCached((*it)->repoInfo()))
- {
- y2milestone("Removing cache for '%s'...", repo_alias.c_str());
- repomanager.cleanCache((*it)->repoInfo());
- }
-
- repomanager.getRepositoryInfo(repo_alias);
- y2milestone("Removing repository '%s'", repo_alias.c_str());
- repomanager.removeRepository((*it)->repoInfo());
- }
- catch (const zypp::repo::RepoNotFoundException &ex)
- {
- // repository not found -- not critical, continue
- y2warning("No such repository: %s", repo_alias.c_str());
- }
- catch (const zypp::Exception & excpt)
- {
- y2error("Pkg::SourceSaveAll has failed: %s", excpt.msg().c_str() );
- _last_error.setLastError(ExceptionAsString(excpt));
- return YCPBoolean(false);
- }
- }
- }
-
- // save all repos (the current configuration)
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- if (!(*it)->isDeleted())
- {
- std::string current_alias = (*it)->repoInfo().alias();
-
- try
- {
- try
- {
- // if the repository already exists then just modify it
- repomanager.getRepositoryInfo(current_alias);
- y2milestone("Modifying repository '%s'", current_alias.c_str());
- repomanager.modifyRepository(current_alias, (*it)->repoInfo());
- }
- catch (const zypp::repo::RepoNotFoundException &ex)
- {
- // the repository was not found, add it
- y2milestone("Adding repository '%s'", current_alias.c_str());
- repomanager.addRepository((*it)->repoInfo());
- }
- }
- catch (zypp::Exception & excpt)
- {
- y2error("Pkg::SourceSaveAll has failed: %s", excpt.msg().c_str() );
- _last_error.setLastError(ExceptionAsString(excpt));
- return YCPBoolean(false);
- }
- }
- }
-
- y2milestone("All sources have been saved");
-
- return YCPBoolean(true);
-}
-
-/****************************************************************************************
- * @builtin SourceFinishAll
- *
- * @short Save and then disable all InstSrces.
- * @description
- * If there are no enabled sources, do nothing
- * (idempotence hack, broken design: #155459, #176013, use SourceSaveAll).
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceFinishAll ()
-{
- try
- {
- bool found_enabled = false;
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- if ((*it)->repoInfo().enabled() && !(*it)->isDeleted())
- {
- found_enabled = true;
- break;
- }
- }
-
- if (!found_enabled)
- {
- y2milestone( "No enabled sources, skipping SourceFinishAll()" );
- return YCPBoolean( true );
- }
-
- SourceSaveAll();
-
- y2milestone( "Disabling all sources...") ;
- for (std::vector<YRepo_Ptr>::iterator it = repos.begin();
- it != repos.end(); ++it)
- {
- (*it)->repoInfo().setEnabled(false);
- }
- // TODO FIXME remove all resolvables??
- }
- catch (zypp::Exception & excpt)
- {
- y2error("Pkg::SourceFinishAll has failed: %s", excpt.msg().c_str() );
- _last_error.setLastError(ExceptionAsString(excpt));
- return YCPBoolean(false);
- }
-
- y2milestone("All sources have been saved and disabled");
-
- return YCPBoolean(true);
-}
-
-/////////////////////////////////////////////////////////////////////////////////////////
-// Query individual sources
-/////////////////////////////////////////////////////////////////////////////////////////
-
-/****************************************************************************************
- * @builtin SourceGeneralData
- *
- * @short Get general data about the source
- * @description
- * Return general data about the source as a map:
- *
- * <code>
- * $[
- * "enabled" : YCPBoolean,
- * "autorefresh": YCPBoolean,
- * "product_dir": YCPString,
- * "type" : YCPString,
- * "url" : YCPString (without password, but see SourceURL),
- * "alias" : YCPString,
- * "name" : YCPString,
- * ];
- *
- * </code>
- * @param integer SrcId Specifies the InstSrc to query.
- * @return map
- **/
-YCPValue
-PkgModuleFunctions::SourceGeneralData (const YCPInteger& id)
-{
- YCPMap data;
-
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPVoid ();
-
- // convert type to the old strings ("YaST", "YUM" or "Plaindir")
- std::string srctype = zypp2yastType(repo->repoInfo().type().asString());
-
- data->add( YCPString("enabled"), YCPBoolean(repo->repoInfo().enabled()));
- data->add( YCPString("autorefresh"), YCPBoolean(repo->repoInfo().autorefresh()));
- data->add( YCPString("type"), YCPString(srctype));
- data->add( YCPString("product_dir"), YCPString(repo->repoInfo().path().asString()));
-
- // check if there is an URL
- if (repo->repoInfo().baseUrlsBegin() != repo->repoInfo().baseUrlsEnd())
- {
- data->add( YCPString("url"), YCPString(repo->repoInfo().baseUrlsBegin()->asString()));
- }
-
- data->add( YCPString("alias"), YCPString(repo->repoInfo().alias()));
- data->add( YCPString("name"), YCPString(repo->repoInfo().name()));
-
- YCPList base_urls;
- for( zypp::RepoInfo::urls_const_iterator it = repo->repoInfo().baseUrlsBegin(); it != repo->repoInfo().baseUrlsEnd(); ++it)
- {
- base_urls->add(YCPString(it->asString()));
- }
- data->add( YCPString("base_urls"), base_urls);
-
- data->add( YCPString("mirror_list"), YCPString(repo->repoInfo().mirrorListUrl().asString()));
-
- return data;
-}
-
-/******************************************************************************
- * @builtin SourceURL
- *
- * @short Get full source URL, including password
- * @param integer SrcId Specifies the InstSrc to query.
- * @return string or nil on failure
- **/
-YCPValue
-PkgModuleFunctions::SourceURL (const YCPInteger& id)
-{
-
- const YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPVoid();
-
- std::string url;
-
- if (repo->repoInfo().baseUrlsBegin() != repo->repoInfo().baseUrlsEnd())
- {
- // #186842
- url = repo->repoInfo().baseUrlsBegin()->asCompleteString();
- }
-
- return YCPString(url);
-}
-
-/****************************************************************************************
- * @builtin SourceMediaData
- * @short Return media data about the source
- * @description
- * Return media data about the source as a map:
- *
- * <code>
- * $["media_count": YCPInteger,
- * "media_id" : YCPString,
- * "media_vendor" : YCPString,
- * "url" : YCPString,
- * ];
- * </code>
- *
- * @param integer SrcId Specifies the InstSrc to query.
- * @return map
- **/
-YCPValue
-PkgModuleFunctions::SourceMediaData (const YCPInteger& id)
-{
- YCPMap data;
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPVoid ();
-
- std::string alias = repo->repoInfo().alias();
- bool found_resolvable = false;
- int max_medium = 1;
-
- for (zypp::ResPool::const_iterator it = zypp_ptr()->pool().begin()
- ; it != zypp_ptr()->pool().end()
- ; ++it)
- {
- if (it->resolvable()->repository().info().alias() == alias)
- {
- int medium = it->resolvable()->mediaNr();
-
- if (medium > max_medium)
- {
- max_medium = medium;
- }
- }
- }
-
- if (found_resolvable)
- {
- data->add( YCPString("media_count"), YCPInteger(max_medium));
- }
- else
- {
- y2error("No resolvable from repository '%s' found, cannot get number of media (use Pkg::SourceLoad() to load the resolvables)", alias.c_str());
- }
-
- y2warning("Pkg::SourceMediaData() doesn't return \"media_id\" and \"media_vendor\" values anymore.");
-
- // SourceMediaData returns URLs without password
- if (repo->repoInfo().baseUrlsBegin() != repo->repoInfo().baseUrlsEnd())
- {
- data->add( YCPString("url"), YCPString(repo->repoInfo().baseUrlsBegin()->asString()));
-
- // add all base URLs
- YCPList base_urls;
- for( zypp::RepoInfo::urls_const_iterator it = repo->repoInfo().baseUrlsBegin(); it != repo->repoInfo().baseUrlsEnd(); ++it)
- {
- base_urls->add(YCPString(it->asString()));
- }
- data->add( YCPString("base_urls"), base_urls);
- }
-
- return data;
-}
-
-/****************************************************************************************
- * @builtin SourceProductData
- * @short Return Product data about the source
- * @param integer SrcId Specifies the InstSrc to query.
- * @description
- * Product data about the source as a map:
- *
- * <code>
- * $[
- * "label" : YCPString,
- * "vendor" : YCPString,
- * "productname" : YCPString,
- * "productversion" : YCPString,
- * "relnotesurl" : YCPString,
- * ];
- * </code>
- *
- * @return map
- **/
-YCPValue
-PkgModuleFunctions::SourceProductData (const YCPInteger& src_id)
-{
- YCPMap ret;
-
- try
- {
- // find a product for the given source
- zypp::ResPool::byKind_iterator it = zypp_ptr()->pool().byKindBegin(zypp::ResTraits<zypp::Product>::kind);
-
- for( ; it != zypp_ptr()->pool().byKindEnd(zypp::ResTraits<zypp::Product>::kind) ; ++it)
- {
- zypp::Product::constPtr product = boost::dynamic_pointer_cast<const zypp::Product>( it->resolvable() );
-
- if( logFindAlias(product->repository().info().alias()) == src_id->value() )
- {
- ret->add( YCPString("label"), YCPString( product->summary() ) );
- ret->add( YCPString("vendor"), YCPString( product->vendor() ) );
- ret->add( YCPString("productname"), YCPString( product->name() ) );
- ret->add( YCPString("productversion"), YCPString( product->edition().version() ) );
- ret->add( YCPString("relnotesurl"), YCPString( product->releaseNotesUrl().asString()));
-
- #warning SourceProductData not finished
- /*
- data->add( YCPString("datadir"), YCPString( descr->content_datadir().asString() ) );
- TODO (?): "baseproductname", "baseproductversion", "defaultbase", "architectures",
- "requires", "linguas", "labelmap", "language", "timezone", "descrdir", "datadir"
- */
-
- break;
- }
- }
-
- if( it == zypp_ptr()->pool().byKindEnd(zypp::ResTraits<zypp::Product>::kind) )
- {
- y2error ("Product for source '%lld' not found", src_id->value());
- }
- }
- catch (...)
- {
- }
-
- return ret;
-}
-
-/****************************************************************************************
- * @builtin SourceProduct
- * @short Obsoleted function, do not use, see SourceProductData builtin
- * @deprecated
- * @param integer
- * @return map empty map
- **/
-YCPValue
-PkgModuleFunctions::SourceProduct (const YCPInteger& id)
-{
- /* TODO FIXME */
- y2error("Pkg::SourceProduct() is obsoleted, use Pkg::SourceProductData() instead!");
- return YCPMap();
-}
-
-
-YCPValue PkgModuleFunctions::SourceProvideFileCommon(const YCPInteger &id,
- const YCPInteger &mid,
- const YCPString& f,
- const YCPBoolean & optional)
-{
- CallInitDownload(std::string(_("Downloading ") + f->value()));
-
- bool found = true;
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- found = false;
-
- extern ZyppRecipients::MediaChangeSensitivity _silent_probing;
- // remember the current value
- ZyppRecipients::MediaChangeSensitivity _silent_probing_old = _silent_probing;
-
- // disable media change callback for optional file
- if (optional->value())
- _silent_probing = ZyppRecipients::MEDIA_CHANGE_OPTIONALFILE;
-
- zypp::filesystem::Pathname path; // FIXME use ManagedMedia
- if (found)
- {
- try
- {
- path = repo->mediaAccess()->provideFile(f->value(), mid->value());
- y2milestone("local path: '%s'", path.asString().c_str());
- }
- catch (const zypp::Exception& excpt)
- {
- found = false;
-
- if (!optional->value())
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2milestone("File not found: %s", f->value_cstr());
- }
- }
- }
-
- // set the original probing value
- _silent_probing = _silent_probing_old;
-
- CallDestDownload();
-
- if (found)
- {
- return YCPString(path.asString());
- }
- else
- {
- return YCPVoid();
- }
-}
-
-
-/****************************************************************************************
- * @builtin SourceProvideFile
- *
- * @short Make a file available at the local filesystem
- * @description
- * Let an InstSrc provide some file (make it available at the local filesystem).
- *
- * @param integer SrcId Specifies the InstSrc .
- * @param integer medianr Number of the media the file is located on ('1' for the 1st media).
- * @param string file Filename relative to the media root.
- *
- * @return string local path as string
- **/
-YCPValue
-PkgModuleFunctions::SourceProvideFile (const YCPInteger& id, const YCPInteger& mid, const YCPString& f)
-{
- return SourceProvideFileCommon(id, mid, f, false /*optional*/);
-}
-
-/****************************************************************************************
- * @builtin SourceProvideOptionalFile
- *
- * @short Make an optional file available at the local filesystem
- * @description
- * Let an InstSrc provide some file (make it available at the local filesystem).
- * If the file doesn't exist don't ask user for another medium and return nil
- *
- * @param integer SrcId Specifies the InstSrc .
- * @param integer medianr Number of the media the file is located on ('1' for the 1st media).
- * @param string file Filename relative to the media root.
- *
- * @return string local path as string
- **/
-YCPValue
-PkgModuleFunctions::SourceProvideOptionalFile (const YCPInteger& id, const YCPInteger& mid, const YCPString& f)
-{
- return SourceProvideFileCommon(id, mid, f, true /*optional*/);
-}
-
-/****************************************************************************************
- * @builtin SourceProvideDir
- * @short make a directory available at the local filesystem
- * @description
- * Let an InstSrc provide some directory (make it available at the local filesystem) and
- * all the files within it (non recursive).
- *
- * @param integer SrcId Specifies the InstSrc .
- * @param integer medianr Number of the media the file is located on ('1' for the 1st media).
- * @param string dir Directoryname relative to the media root.
- * @return string local path as string
- */
-YCPValue
-PkgModuleFunctions::SourceProvideDir (const YCPInteger& id, const YCPInteger& mid, const YCPString& d)
-{
- y2warning("Pkg::SourceProvideDir() is obsoleted use Pkg::SourceProvideDirectory() instead");
- // non optional, non recursive
- return SourceProvideDirectory(id, mid, d, false, false);
-}
-
-
-/****************************************************************************************
- * @builtin SourceProvideDirectory
- * @short make a directory available at the local filesystem
- * @description
- * Download a directory from repository (make it available at the local filesystem) and
- * all the files within it.
- *
- * @param integer id repository to use (id)
- * @param integer mid Number of the media where the directory is located on ('1' for the 1st media).
- * @param string d Directory name relative to the media root.
- * @param boolean optional set to true if the directory may not exist (do not report errors)
- * @param boolean recursive set to true to provide all subdirectories recursively
- * @return string local path as string or nil when an error occured
- */
-YCPValue
-PkgModuleFunctions::SourceProvideDirectory(const YCPInteger& id, const YCPInteger& mid, const YCPString& d, const YCPBoolean &optional, const YCPBoolean &recursive)
-{
- CallInitDownload(std::string(_("Downloading ") + d->value()));
-
- bool found = true;
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- found = false;
-
- zypp::filesystem::Pathname path; // FIXME user ManagedMedia
-
- extern ZyppRecipients::MediaChangeSensitivity _silent_probing;
- // remember the current value
- ZyppRecipients::MediaChangeSensitivity _silent_probing_old = _silent_probing;
-
- // disable media change callback for optional file
- if (optional->value())
- _silent_probing = ZyppRecipients::MEDIA_CHANGE_OPTIONALFILE;
-
- if (found)
- {
- try
- {
- path = repo->mediaAccess()->provideDir(d->value(), recursive->value(), mid->value());
- }
- catch (const zypp::Exception& excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2milestone ("Directory not found: %s", d->value_cstr());
- found = false;
- }
- }
-
- // set the original probing value
- _silent_probing = _silent_probing_old;
-
- CallDestDownload();
-
- if (found)
- {
- return YCPString(path.asString());
- }
- else
- {
- return YCPVoid();
- }
-}
-
-/****************************************************************************************
- * @builtin SourceChangeUrl
- * @short Change Source URL
- * @description
- * Change url of an InstSrc. Used primarely when re-starting during installation
- * and a cd-device changed from hdX to srX since ide-scsi was activated.
- * @param integer SrcId Specifies the InstSrc.
- * @param string url The new url to use.
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceChangeUrl (const YCPInteger& id, const YCPString& u)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- try
- {
- if (repo->repoInfo().baseUrlsSize() > 1)
- {
- // store current urls
- std::set<zypp::Url> baseUrls (repo->repoInfo().baseUrlsBegin(), repo->repoInfo().baseUrlsEnd());
-
- // reset url list and store the new one there
- repo->repoInfo().setBaseUrl(zypp::Url(u->value()));
-
- // add the rest of base urls
- for (std::set<zypp::Url>::const_iterator i = baseUrls.begin();
- i != baseUrls.end(); ++i)
- repo->repoInfo().addBaseUrl(*i);
- }
- else
- repo->repoInfo().setBaseUrl(zypp::Url(u->value()));
- }
- catch (const zypp::Exception & excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error ("Cannot set the new URL for source %s (%lld): %s",
- repo->repoInfo().alias().c_str(), id->asInteger()->value(), excpt.msg().c_str());
- return YCPBoolean(false);
- }
-
- return YCPBoolean(true);
-}
-
-/****************************************************************************************
- * @builtin SourceInstallOrder
- *
- * @short not implemented, do not use (Explicitly set an install order.)
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceInstallOrder (const YCPMap& ord)
-{
- /* TODO FIXME
- YCPList args;
- args->add (ord);
-
- //-------------------------------------------------------------------------------------//
- YcpArgLoad decl(__FUNCTION__);
-
- YCPMap & order_map( decl.arg<YT_MAP, YCPMap>() );
-
- if ( ! decl.load( args ) ) {
- return pkgError_bad_args;
- }
- //-------------------------------------------------------------------------------------//
-
- InstSrcManager::InstOrder order;
- order.reserve( order_map->size() );
- bool error = false;
-
- for ( YCPMapIterator it = order_map->begin(); it != order_map->end(); ++it ) {
-
- if ( it.value()->isInteger() ) {
- InstSrc::UniqueID uId( it.value()->asInteger()->value() );
- InstSrcManager::ISrcId source_id( _y2pm.instSrcManager().getSourceByID( uId ) );
- if ( source_id ) {
- if ( source_id->enabled() ) {
- order.push_back( uId ); // finaly ;)
-
- } else {
- y2error ("order map entry '%s:%s': source not enabled",
- it.key()->toString().c_str(),
- it.value()->toString().c_str() );
- error = true;
- }
- } else {
- y2error ("order map entry '%s:%s': bad source id",
- it.key()->toString().c_str(),
- it.value()->toString().c_str() );
- error = true;
- }
- } else {
- y2error ("order map entry '%s:%s': integer value expected",
- it.key()->toString().c_str(),
- it.value()->toString().c_str() );
- error = true;
- }
- }
- if ( error ) {
- return pkgError( Error::E_bad_args );
- }
-
- // store new instorder
- _y2pm.instSrcManager().setInstOrder( order );
-*/
-
-#warning SourceInstallOrder is not implemented
- return YCPBoolean( true );
-}
-
-
-static std::string timestamp ()
-{
- time_t t = time(NULL);
- struct tm * tmp = localtime(&t);
-
- if (tmp == NULL) {
- return "";
- }
-
- char outstr[50];
- if (strftime(outstr, sizeof(outstr), "%Y%m%d-%H%M%S", tmp) == 0) {
- return "";
- }
- return outstr;
-}
-
-/**
- * Take the ?alias=foo part of old_url, if any, and return it,
- * putting the rest to new_url.
- * \throws Exception on malformed URLs I guess
- */
-static std::string removeAlias (const zypp::Url & old_url,
- zypp::Url & new_url)
-{
- std::string alias;
- new_url = old_url;
- zypp::url::ParamMap query = new_url.getQueryStringMap ();
- zypp::url::ParamMap::iterator alias_it = query.find ("alias");
- if (alias_it != query.end ())
- {
- alias = alias_it->second;
- query.erase (alias_it);
- new_url.setQueryStringMap (query);
- }
- return alias;
-}
-
-std::string PkgModuleFunctions::UniqueAlias(const std::string &alias)
-{
- // make a copy
- std::string ret = alias;
-
- unsigned int id = 0;
- while(aliasExists(ret))
- {
- y2milestone("Alias %s already found: %lld", ret.c_str(), logFindAlias(ret));
-
- // the alias already exists - add a counter
- std::ostringstream ostr;
- ostr << alias << "_" << id;
-
- ret = ostr.str();
-
- y2milestone("Using alias %s", ret.c_str());
- ++id;
- }
-
- return ret;
-}
-
-
-/**
- * helper - add "mountoptions=ro" for mountable URL schemes if "mountoptions" option is not empty and
- * "rw" or "ro" option is missing
- */
-zypp::Url addRO(const zypp::Url &url)
-{
- zypp::Url ret(url);
- std::string scheme = zypp::str::toLower(url.getScheme());
-
- if (scheme == "nfs"
- || scheme == "hd"
- || scheme == "smb"
- || scheme == "iso"
- || scheme == "cd"
- || scheme == "dvd"
- )
- {
- const std::string mountoptions = "mountoptions";
- zypp::media::Mount::Options options(url.getQueryParam(mountoptions));
-
- y2debug("Current mountoptions: %s", options.asString().c_str());
-
- // if mountoptions are empty lizypp uses "ro" by default
- // don't override "rw" option from application
- // don't add "ro" if it's already present
- if (!options.empty() && !options.has("rw") && !options.has("ro"))
- {
- options["ro"];
-
- ret.setQueryParam(mountoptions, options.asString());
- y2milestone("Adding read only mount option: '%s' -> '%s'", url.asString().c_str(), ret.asString().c_str());
- }
- }
-
- return ret;
-}
-
-// helper function
-zypp::Url PkgModuleFunctions::shortenUrl(const zypp::Url &url)
-{
- std::string url_path = url.getPathName();
- std::string begin_path;
- std::string end_path;
-
- // try to convert 'http://server/dir1/dir2/dir3/dir4' -> 'http://server/dir1/.../dir4'
- std::string::size_type pos_first = url_path.find("/");
- if (pos_first == 0)
- {
- pos_first = url_path.find("/", 1);
- }
-
- if (pos_first == std::string::npos)
- {
- const int num = 5;
-
- // "/" not found use the beginning and the end part
- // 'http://server/very_long_directory_name' -> 'http://server/very_..._name'
- begin_path = std::string(url_path, 0, num);
- end_path = std::string(url_path, url_path.size() - num - 1, num);
- }
- else
- {
- unsigned int pos_last = url_path.rfind("/");
- if (pos_last == url_path.size() - 1)
- {
- pos_last = url_path.rfind("/", url_path.size() - 1);
- }
-
- if (pos_last == pos_first || pos_last < pos_first)
- {
- const int num = 5;
-
- // "/" not found use the beginning and the end part
- begin_path = std::string(url_path, 0, num);
- end_path = std::string(url_path, url_path.size() - num - 1, num);
- }
- else
- {
- begin_path = std::string(url_path, 0, pos_first + 1);
- end_path = std::string(url_path, pos_last);
- }
- }
-
- std::string new_path = begin_path + "..." + end_path;
- zypp::Url ret(url);
-
- // use the shorter path
- ret.setPathName(new_path);
- // remove query parameters
- ret.setQueryString("");
- // remove fragmet
- ret.setFragment("");
-
- y2milestone("Using shortened URL: '%s' -> '%s'", url.asString().c_str(), ret.asString().c_str());
- return ret;
-}
-
-/** Create a Source and immediately put it into the SourceManager.
- * \return the SourceId
- * \throws Exception if Source creation fails
-*/
-std::vector<zypp::RepoInfo>::size_type
-PkgModuleFunctions::createManagedSource( const zypp::Url & url_r,
- const zypp::Pathname & path_r,
- const bool base_source,
- const std::string& type,
- const std::string &alias_r )
-{
- // parse URL
- y2milestone ("Original URL: %s, product directory: %s", url_r.asString().c_str(), path_r.asString().c_str());
-
- // #158850#c17, if the URL contains an alias, we use that
- zypp::Url url;
-
- std::string alias = removeAlias(url_r, url);
- y2milestone("Alias from URL: '%s'", alias.c_str());
-
-#warning FIXME: use base_source (base_source vs. addon) (will be probably not needed)
-
- // repository type
- zypp::repo::RepoType repotype;
- zypp::RepoManager repomanager = CreateRepoManager();
-
- if (!type.empty())
- {
- try
- {
- // do conversion from the Yast type ("YaST", "YUM", "Plaindir")
- // to libzypp type ("yast", "yum", "plaindir")
- repotype = repotype.parse(yast2zyppType(type));
- }
- catch (zypp::repo::RepoUnknownTypeException &e)
- {
- y2warning("Unknown source type '%s'", type.c_str());
- }
- }
-
- // the type is not specified or is wrong, autoprobe the type
- if (repotype == zypp::repo::RepoType::NONE)
- {
- zypp::Url probe_url(url_r);
-
- if (!path_r.asString().empty())
- {
- zypp::Pathname pth(probe_url.getPathName());
- pth /= path_r;
-
- probe_url.setPathName(pth.asString());
- }
-
- y2milestone("Probing source type: '%s'", probe_url.asString().c_str());
-
- // autoprobe type of the repository
- repotype = ProbeWithCallbacks(probe_url);
- }
-
- y2milestone("Using source type: %s", repotype.asString().c_str());
-
-
- // create source definition object
- zypp::RepoInfo repo;
-
- std::string name;
-
- // set alias and name
- if (alias.empty())
- {
- // alias not set via URL, use the passed alias or the URL path
- if (alias_r.empty())
- {
- // use the last path element in URL
- std::string url_path = url.getPathName();
-
- std::string::size_type pos_begin = url_path.rfind("/");
- std::string::size_type pos_end = std::string::npos;
-
- // ignore the trailing slash
- if (pos_begin == url_path.size() - 1)
- {
- pos_begin = url_path.rfind("/", url_path.size() - 2);
-
- if (pos_begin != std::string::npos)
- {
- pos_end = url_path.size() - pos_begin - 2;
- }
- }
- else
- {
- pos_end = url_path.size() - pos_begin - 1;
- }
-
- // ignore the found slash character
- pos_begin++;
-
- alias = std::string(url_path, pos_begin, pos_end);
-
- y2milestone("Alias from URL path: %s", alias.c_str());
-
- // fallback
- if (alias.empty())
- {
- y2milestone("URL alias is empty using 'Repository'");
- alias = "Repository";
- }
- }
- else
- {
- alias = alias_r;
- }
-
- name = alias;
- }
- else
- {
- name = alias;
- }
-
-
- y2milestone("Name of the repository: '%s'", name.c_str());
-
- // alias must be unique, add a suffix if it's already used
- alias = UniqueAlias(alias);
-
- // add read only mount option to the URL if needed
- url = addRO(url);
-
- bool autorefresh = true;
-
- std::string scheme = zypp::str::toLower(url.getScheme());
- if (scheme == "cd" || scheme == "dvd")
- {
- y2milestone("Disabling autorefresh for CD/DVD repository");
- autorefresh = false;
- }
-
- repo.setAlias(alias);
- repo.setName(name);
- repo.setType(repotype);
- repo.addBaseUrl(url);
- repo.setPath(path_r);
- repo.setEnabled(true);
- repo.setAutorefresh(autorefresh);
-
- // set metadata path (#293428)
- zypp::Pathname metadatapath = repomanager.metadataPath(repo);
- repo.setMetadataPath(metadatapath);
-
- y2milestone("Adding source '%s' (%s, dir: %s)", repo.alias().c_str(), url.asString().c_str(), path_r.asString().c_str());
- // note: exceptions should be caught by the calling code
- RefreshWithCallbacks(repo);
-
- // build cache if needed
- if (!repomanager.isCached(repo))
- {
- y2milestone("Caching source '%s'...", repo.alias().c_str());
- repomanager.buildCache(repo);
- }
-
- repos.push_back(new YRepo(repo));
-
- y2milestone("Added source '%s': '%s', enabled: %s, autorefresh: %s",
- repo.alias().c_str(),
- repo.baseUrlsBegin()->asString().c_str(),
- repo.enabled() ? "true" : "false",
- repo.autorefresh() ? "true" : "false"
- );
-
- // the source is at the end of the list
- return repos.size() - 1;
-}
-
-/****************************************************************************************
- * @builtin RepositoryAdd
- *
- * @short Register a new repository
- * @description
- * Adds a new repository to the internal structures. The repository is only registered,
- * metadata is not downloaded, use Pkg::SourceRefreshNow() for that. The metadata is also loaded
- * automatically when loading the repository content (Pkg::SourceLoad())
- *
- * @param map map with repository parameters: $[ "enabled" : boolean, "autorefresh" : boolean, "name" : string,
- * "alias" : string, "base_urls" : list<string>, "prod_dir" : string, "type" : string ]
- * @return integer Repository ID or nil on error
- **/
-YCPValue PkgModuleFunctions::RepositoryAdd(const YCPMap ¶ms)
-{
- zypp::RepoInfo repo;
-
- // turn on the repo by default
- repo.setEnabled(true);
- // enable autorefresh by default
- repo.setAutorefresh(true);
-
- if (!params->value( YCPString("enabled") ).isNull() && params->value(YCPString("enabled"))->isBoolean())
- {
- repo.setEnabled(params->value(YCPString("enabled"))->asBoolean()->value());
- }
-
- if (!params->value( YCPString("autorefresh") ).isNull() && params->value(YCPString("autorefresh"))->isBoolean())
- {
- repo.setAutorefresh(params->value(YCPString("autorefresh"))->asBoolean()->value());
- }
-
- std::string alias;
-
- if (!params->value( YCPString("alias") ).isNull() && params->value(YCPString("alias"))->isString())
- {
- alias = params->value(YCPString("alias"))->asString()->value();
- }
-
- if (alias.empty())
- {
- alias = timestamp();
-
- // the alias must be unique
- alias = UniqueAlias(alias);
- }
- else
- {
- if (aliasExists(alias))
- {
- ycperror("alias %s already exists", alias.c_str());
- return YCPVoid();
- }
- }
-
- repo.setAlias(alias);
-
- // use the first base URL as a fallback name
- std::string first_url;
-
- if (!params->value( YCPString("base_urls") ).isNull() && params->value(YCPString("base_urls"))->isList())
- {
- YCPList lst(params->value(YCPString("base_urls"))->asList());
-
- for (int index = 0; index < lst->size(); ++index)
- {
- if( ! lst->value(index)->isString() )
- {
- ycperror( "Pkg::RepositoryAdd(): entry not a string at index %d: %s", index, lst->toString().c_str());
- return YCPVoid();
- }
-
- zypp::Url url;
-
- try
- {
- url = lst->value(index)->asString()->value();
- zypp::Url url_new;
-
- std::string name = removeAlias(url, url_new);
-
- if (!name.empty())
- {
- repo.setName(name);
- url = url_new;
- }
-
- // add read only mount option to the URL if needed
- url = addRO(url);
- }
- catch(const zypp::Exception & expt)
- {
- y2error("Invalid URL: %s", expt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(expt));
- return YCPVoid();
- }
-
- if (index == 0)
- {
- first_url = url.asString();
- }
-
- repo.addBaseUrl(url);
- }
- }
- else
- {
- ycperror("Missing \"base_urls\" key in the map");
- return YCPVoid();
- }
-
- // check name parameter
- if (!params->value( YCPString("name") ).isNull() && params->value(YCPString("name"))->isString())
- {
- repo.setName(params->value(YCPString("name"))->asString()->value());
- }
- else
- {
- // if the key "name" is missing and the name hasn't been set by ?alias= in the URL
- // then use the first URL as the name
- if (repo.name().empty())
- {
- repo.setName(first_url);
- }
- }
-
- if (!params->value( YCPString("type") ).isNull() && params->value(YCPString("type"))->isString())
- {
- std::string type = yast2zyppType(params->value(YCPString("type"))->asString()->value());
-
- try
- {
- zypp::repo::RepoType repotype(type);
- repo.setType(repotype);
- }
- catch (zypp::repo::RepoUnknownTypeException &e)
- {
- ycperror("Unknown source type '%s': %s", type.c_str(), e.asString().c_str());
- _last_error.setLastError(ExceptionAsString(e));
- return YCPVoid();
- }
-
- }
-
- if (!params->value( YCPString("prod_dir") ).isNull() && params->value(YCPString("prod_dir"))->isString())
- {
- repo.setPath(params->value(YCPString("prod_dir"))->asString()->value());
- }
-
- // set metadata path (#293428)
- zypp::RepoManager repomanager = CreateRepoManager();
- zypp::Pathname metadatapath = repomanager.metadataPath(repo);
- repo.setMetadataPath(metadatapath);
-
- repos.push_back(new YRepo(repo));
-
- // the new source is at the end of the list
- return YCPInteger(repos.size() - 1);
-}
-
-/****************************************************************************************
- * @builtin SourceCacheCopyTo
- *
- * @short Copy cache data of all installation sources to the target
- * @description
- * Copy cache data of all installation sources to the target located below 'dir'.
- * To be called at end of initial installation.
- *
- * @param string dir Root directory of target.
- * @return boolean true on success
- **/
-YCPValue
-PkgModuleFunctions::SourceCacheCopyTo (const YCPString& dir)
-{
- // error message (followed by detailed description)
- const std::string msg = _("Error: Cannot copy the cache to the target directory\n");
-
- std::string d = dir->value();
- y2milestone("Copying source cache to '%s'...", d.c_str());
-
- if (d.empty())
- {
- y2error("Empty parameter in Pkg::SourceCacheCopyTo()!");
- return YCPBoolean(false);
- }
-
- std::string target = d + "/var/cache";
-
- // create the target dir
- const char* argv[] =
- {
- "mkdir",
- // create parent dir
- "-p",
- // finish parameter list
- "--",
- // target
- target.c_str(),
- NULL
- };
-
- // discard stderr, no pty, stderr_fd = -1, use the default locale
- zypp::ExternalProgram prog(argv, zypp::ExternalProgram::Discard_Stderr, false, -1, true);
-
- int code = prog.close();
-
- if (code)
- {
- // error message (followed by directory name)
- _last_error.setLastError(msg + _("Cannot create directory ") + target);
- y2error("Cannot create target directory %s", target.c_str());
- return YCPBoolean(false);
- }
-
- // copy /var/cache/zypp to the target system
- const char* argv2[] =
- {
- "cp",
- // preserve time stamps
- "-a",
- // recursive
- "-r",
- // finish parameter list
- "--",
- // source
- "/var/cache/zypp",
- // target
- target.c_str(),
- NULL
- };
-
- // discard stderr, no pty, stderr_fd = -1, use the default locale
- zypp::ExternalProgram prog2(argv2, zypp::ExternalProgram::Discard_Stderr, false, -1, true);
-
- int code2 = prog2.close();
-
- if (code2)
- {
- // error message
- _last_error.setLastError(msg + _("Copying failed"));
- y2error("Cannot copy /var/cache/zypp to %s", d.c_str());
- }
-
- return YCPBoolean(!code2);
-}
-
-/****************************************************************************************
- * @builtin SourceScan
- * @short Scan a Source Media
- * @description
- * Load all InstSrces found at media_url, i.e. all sources mentioned in /media.1/products.
- * If no /media.1/products is available, InstSrc is expected to be located directly
- * below media_url (product_dir: /).
- *
- * If a product_dir is provided, only the InstSrc located at media_url/product_dir is loaded.
- *
- * In contrary to @ref SourceCreate, InstSrces are loaded into the InstSrcManager,
- * but not enabled (packages and selections are not provided to the PackageManager),
- * and the SrcIds of <b>all</b> InstSrces found are returned.
- *
- * @param string url The media to scan.
- * @optarg string product_dir Restrict scan to a certain InstSrc located in media_url/product_dir.
- *
- * @return list<integer> list of SrcIds (integer).
- **/
-YCPValue
-PkgModuleFunctions::SourceScan (const YCPString& media, const YCPString& pd)
-{
- zypp::Url url;
-
- try {
- url = zypp::Url(media->value ());
- }
- catch(const zypp::Exception & expt )
- {
- y2error ("Invalid URL: %s", expt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(expt));
- return YCPList();
- }
-
- zypp::Pathname pn(pd->value ());
-
- YCPList ids;
- std::vector<zypp::RepoInfo>::size_type id;
-
- if ( pd->value().empty() ) {
-
- // scan all sources
- zypp::MediaProductSet products;
-
- try
- {
- y2milestone("Scanning products in %s ...", url.asString().c_str());
- ScanProductsWithCallBacks(url);
- products = available_products;
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("Scanning products for '%s' has failed"
- , url.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- return ids;
- }
-
- if( products.empty() )
- {
- // no products found, use the base URL instead
- zypp::MediaProductEntry entry;
- products.insert(entry);
- }
-
- for( zypp::MediaProductSet::const_iterator it = products.begin();
- it != products.end() ; ++it )
- {
- try
- {
- y2milestone("Using product %s in directory %s", it->_name.c_str(), it->_dir.c_str());
- id = createManagedSource(url, it->_dir, false, "", it->_name);
- ids->add( YCPInteger(id) );
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("SourceScan for '%s' product '%s' has failed"
- , url.asString().c_str(), pn.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- }
- }
- } else {
- y2debug("Creating source...");
-
- try
- {
- id = createManagedSource(url, pn, false, "", "");
- ids->add( YCPInteger(id) );
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("SourceScan for '%s' product '%s' has failed"
- , url.asString().c_str(), pn.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- }
- }
-
- y2milestone("Found sources: %s", ids->toString().c_str() );
-
- return ids;
-}
-
-/****************************************************************************************
- * @builtin SourceCreate
- *
- * @short Create a Source
- * @description
- * Load and enable all InstSrces found at media_url, i.e. all sources mentioned in /media.1/products.
- * If no /media.1/products is available, InstSrc is expected to be located directly below
- * media_url (product_dir: /).
- *
- * If a product_dir is provided, only the InstSrc located at media_url/product_dir is loaded
- * and enabled.
- *
- * @param string url The media to scan.
- * @optarg string product_dir Restrict scan to a certain InstSrc located in media_url/product_dir.
- *
- * @return integer The source_id of the first InstSrc found on the media.
- **/
-YCPValue
-PkgModuleFunctions::SourceCreate (const YCPString& media, const YCPString& pd)
-{
- // not base product, autoprobe source type
- return SourceCreateEx (media, pd, false, YCPString(""));
-}
-
-YCPValue
-PkgModuleFunctions::SourceCreateBase (const YCPString& media, const YCPString& pd)
-{
- // base product, autoprobe source type
- return SourceCreateEx (media, pd, true, YCPString(""));
-}
-
-/**
- * @builtin SourceCreateType
- * @short Create source of required type
- * @description
- * Create a source without autoprobing the source type. This builtin should be used only for "Plaindir" sources, because Plaindir sources are not automatically probed in SourceCreate() builtin.
- * @param media URL of the source
- * @param pd product directory (if empty the products will be searched)
- * @param type type of the source ("YaST", "YUM" or "Plaindir")
-*/
-
-YCPValue
-PkgModuleFunctions::SourceCreateType (const YCPString& media, const YCPString& pd, const YCPString& type)
-{
- // not base product, autoprobe source type
- return SourceCreateEx (media, pd, false, type);
-}
-
-YCPValue
-PkgModuleFunctions::SourceCreateEx (const YCPString& media, const YCPString& pd, bool base, const YCPString& source_type)
-{
- y2debug("Creating source...");
-
- zypp::Pathname pn(pd->value ());
-
- zypp::Url url;
-
- try {
- url = zypp::Url(media->value ());
- }
- catch(const zypp::Exception & expt )
- {
- y2error ("Invalid URL: %s", expt.asString().c_str());
- _last_error.setLastError(ExceptionAsString(expt));
- return YCPInteger (-1LL);
- }
-
-
- YCPList ids;
- std::vector<zypp::RepoInfo>::size_type ret = -1;
-
- const std::string type = source_type->value();
-
- if ( pd->value().empty() ) {
- // scan all sources
- zypp::MediaProductSet products;
-
- try {
- ScanProductsWithCallBacks(url);
- products = available_products;
- }
- catch ( const zypp::Exception& excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error( "Cannot read the product list from the media" );
- return YCPInteger(-1LL);
- }
-
- if( products.empty() )
- {
- // no products found, use the base URL instead
- zypp::MediaProductEntry entry ;
- products.insert( entry );
- }
-
- for( zypp::MediaProductSet::const_iterator it = products.begin();
- it != products.end() ; ++it )
- {
- try
- {
- std::vector<zypp::RepoInfo>::size_type id = createManagedSource(url, it->_dir, base, type, it->_name);
- YRepo_Ptr repo = logFindRepository(id);
-
- LoadResolvablesFrom(repo->repoInfo());
-
- // return the id of the first product
- if ( it == products.begin() )
- ret = id;
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("SourceCreate for '%s' product '%s' has failed"
- , url.asString().c_str(), pn.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- return YCPInteger(-1LL);
- }
- }
- } else {
- y2debug("Creating source...");
-
- try
- {
- ret = createManagedSource(url, pn, base, type, "");
-
- YRepo_Ptr repo = logFindRepository(ret);
- repo->repoInfo().setEnabled(true);
-
- LoadResolvablesFrom(repo->repoInfo());
- }
- catch ( const zypp::Exception& excpt)
- {
- y2error("SourceCreate for '%s' product '%s' has failed"
- , url.asString().c_str(), pn.asString().c_str());
- _last_error.setLastError(ExceptionAsString(excpt));
- }
- }
-
- PkgFreshen();
- return YCPInteger(repos.size() - 1);
-}
-
-
-/****************************************************************************************
- * @builtin SourceSetEnabled
- *
- * @short Set the default activation state of an InsrSrc.
- * @param integer SrcId Specifies the InstSrc.
- * @param boolean enabled Default activation state of source.
- *
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceSetEnabled (const YCPInteger& id, const YCPBoolean& e)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- // no change required
- bool enable = e->value();
- if ((enable && repo->repoInfo().enabled())
- || (!enable && !repo->repoInfo().enabled()))
- return YCPBoolean(true);
-
- bool success = true;
-
- try
- {
- repo->repoInfo().setEnabled(enable);
-
- // add/remove resolvables
- if (enable)
- {
- // load resolvables only when they are missing
- if (!AnyResolvableFrom(repo->repoInfo().alias()))
- {
- success = LoadResolvablesFrom(repo->repoInfo());
- }
- }
- else
- {
- // the source has been disabled, remove resolvables from the pool
- RemoveResolvablesFrom(repo->repoInfo().alias());
- }
-
- PkgFreshen();
- }
- catch (const zypp::Exception& excpt)
- {
- std::string alias = repo->repoInfo().alias();
- y2error ("Error for '%s': %s", alias.c_str(), excpt.asString().c_str());
- _last_error.setLastError(alias + ": " + ExceptionAsString(excpt));
- success = false;
- }
-
- return YCPBoolean(success);
-}
-
-/****************************************************************************************
- * @builtin SourceSetAutorefresh
- *
- * @short Set whether this source should automaticaly refresh it's
- * meta data when it gets enabled. (default true, if not CD/DVD)
- * @param integer SrcId Specifies the InstSrc.
- * @param boolean enabled Whether autorefresh should be turned on or off.
+/* ------------------------------------------------------------------------------
+ * Copyright (c) 2007 Novell, Inc. All Rights Reserved.
*
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceSetAutorefresh (const YCPInteger& id, const YCPBoolean& e)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
-
- repo->repoInfo().setAutorefresh(e->value());
-
- return YCPBoolean( true );
-}
-
-/****************************************************************************************
- * @builtin SourceFinish
- * @short Disable an Installation Source
- * @param integer SrcId Specifies the InstSrc.
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceFinish (const YCPInteger& id)
-{
- return SourceSetEnabled(id, false);
-}
-
-/****************************************************************************************
- * @builtin SourceRefreshNow
- * @short Attempt to immediately refresh a Source
- * @description
- * The InsrSrc will be encouraged to check and refresh all metadata
- * cached on disk.
*
- * @param integer SrcId Specifies the InstSrc.
+ * This program is free software; you can redistribute it and/or modify it under
+ * the terms of version 2 of the GNU General Public License as published by the
+ * Free Software Foundation.
*
- * @return boolean
- **/
-YCPValue
-PkgModuleFunctions::SourceRefreshNow (const YCPInteger& id)
-{
- YRepo_Ptr repo = logFindRepository(id->value());
- if (!repo)
- return YCPBoolean(false);
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+ * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along with
+ * this program; if not, contact Novell, Inc.
+ *
+ * To contact Novell about this file by physical or electronic mail, you may find
+ * current contact information at www.novell.com.
+ * ------------------------------------------------------------------------------
+ */
- try
- {
- zypp::RepoManager repomanager = CreateRepoManager();
- y2milestone("Refreshing metadata '%s'", repo->repoInfo().alias().c_str());
- RefreshWithCallbacks(repo->repoInfo());
+/*
+ File: $Id:$
+ Author: Ladislav Slezák <lslezak(a)novell.com>
+ Summary: Functions for changing properties of a repository
+*/
- y2milestone("Caching source '%s'...", repo->repoInfo().alias().c_str());
- repomanager.buildCache(repo->repoInfo());
- }
- catch ( const zypp::Exception & expt )
- {
- y2error ("Error while refreshing the source: %s", expt.asString().c_str());
- _last_error.setLastError(repo->repoInfo().alias() + ": " + ExceptionAsString(expt));
- return YCPBoolean(false);
- }
+#include <Callbacks.h>
+#include <Callbacks.YCP.h>
+
+#include <PkgModule.h>
+#include <PkgModuleFunctions.h>
- return YCPBoolean( true );
-}
/****************************************************************************************
- * @builtin SourceDelete
- * @short Delete a Source
- * @description
- * Delete an InsrSrc. The InsrSrc together with all metadata cached on disk
- * is removed. The SrcId passed becomes invalid (other SrcIds stay valid).
+ * @builtin SourceSetEnabled
*
+ * @short Set the default activation state of an InsrSrc.
* @param integer SrcId Specifies the InstSrc.
+ * @param boolean enabled Default activation state of source.
*
* @return boolean
**/
YCPValue
-PkgModuleFunctions::SourceDelete (const YCPInteger& id)
+PkgModuleFunctions::SourceSetEnabled (const YCPInteger& id, const YCPBoolean& e)
{
YRepo_Ptr repo = logFindRepository(id->value());
if (!repo)
return YCPBoolean(false);
+ // no change required
+ bool enable = e->value();
+ if ((enable && repo->repoInfo().enabled())
+ || (!enable && !repo->repoInfo().enabled()))
+ return YCPBoolean(true);
+
bool success = true;
try
{
- // the resolvables cannot be used anymore, remove them
- RemoveResolvablesFrom(repo->repoInfo().alias());
+ repo->repoInfo().setEnabled(enable);
- // update 'repos'
- repo->setDeleted();
+ // add/remove resolvables
+ if (enable)
+ {
+ // load resolvables only when they are missing
+ if (!AnyResolvableFrom(repo->repoInfo().alias()))
+ {
+ success = LoadResolvablesFrom(repo->repoInfo());
+ }
+ }
+ else
+ {
+ // the source has been disabled, remove resolvables from the pool
+ RemoveResolvablesFrom(repo->repoInfo().alias());
+ }
PkgFreshen();
}
@@ -2461,44 +88,25 @@
}
/****************************************************************************************
- * @builtin SourceEditGet
+ * @builtin SourceSetAutorefresh
*
- * @short Get state of Sources
- * @description
- * Return a list of states for all known InstSources sorted according to the
- * source priority (highest first). A source state is a map:
- * $[
- * "SrcId" : YCPInteger,
- * "enabled" : YCPBoolean
- * "autorefresh": YCPBoolean
- * ];
+ * @short Set whether this source should automaticaly refresh it's
+ * meta data when it gets enabled. (default true, if not CD/DVD)
+ * @param integer SrcId Specifies the InstSrc.
+ * @param boolean enabled Whether autorefresh should be turned on or off.
*
- * @return list<map> list of source states (map)
+ * @return boolean
**/
YCPValue
-PkgModuleFunctions::SourceEditGet ()
+PkgModuleFunctions::SourceSetAutorefresh (const YCPInteger& id, const YCPBoolean& e)
{
- YCPList ret;
-
- unsigned long index = 0;
- for( std::vector<YRepo_Ptr>::const_iterator it = repos.begin(); it != repos.end(); ++it, ++index)
- {
- if (!(*it)->isDeleted())
- {
- YCPMap src_map;
-
- src_map->add(YCPString("SrcId"), YCPInteger(index));
- // Note: enabled() is tribool
- src_map->add(YCPString("enabled"), YCPBoolean((*it)->repoInfo().enabled()));
- // Note: autorefresh() is tribool
- src_map->add(YCPString("autorefresh"), YCPBoolean((*it)->repoInfo().autorefresh()));
- src_map->add(YCPString("name"), YCPString((*it)->repoInfo().name()));
+ YRepo_Ptr repo = logFindRepository(id->value());
+ if (!repo)
+ return YCPBoolean(false);
- ret->add(src_map);
- }
- }
+ repo->repoInfo().setAutorefresh(e->value());
- return ret;
+ return YCPBoolean( true );
}
/****************************************************************************************
@@ -2583,6 +191,52 @@
return YCPBoolean( !error );
}
+/****************************************************************************************
+ * @builtin SourceChangeUrl
+ * @short Change Source URL
+ * @description
+ * Change url of an InstSrc. Used primarely when re-starting during installation
+ * and a cd-device changed from hdX to srX since ide-scsi was activated.
+ * @param integer SrcId Specifies the InstSrc.
+ * @param string url The new url to use.
+ * @return boolean
+ **/
+YCPValue
+PkgModuleFunctions::SourceChangeUrl (const YCPInteger& id, const YCPString& u)
+{
+ YRepo_Ptr repo = logFindRepository(id->value());
+ if (!repo)
+ return YCPBoolean(false);
+
+ try
+ {
+ if (repo->repoInfo().baseUrlsSize() > 1)
+ {
+ // store current urls
+ std::set<zypp::Url> baseUrls (repo->repoInfo().baseUrlsBegin(), repo->repoInfo().baseUrlsEnd());
+
+ // reset url list and store the new one there
+ repo->repoInfo().setBaseUrl(zypp::Url(u->value()));
+
+ // add the rest of base urls
+ for (std::set<zypp::Url>::const_iterator i = baseUrls.begin();
+ i != baseUrls.end(); ++i)
+ repo->repoInfo().addBaseUrl(*i);
+ }
+ else
+ repo->repoInfo().setBaseUrl(zypp::Url(u->value()));
+ }
+ catch (const zypp::Exception & excpt)
+ {
+ _last_error.setLastError(ExceptionAsString(excpt));
+ y2error ("Cannot set the new URL for source %s (%lld): %s",
+ repo->repoInfo().alias().c_str(), id->asInteger()->value(), excpt.msg().c_str());
+ return YCPBoolean(false);
+ }
+
+ return YCPBoolean(true);
+}
+
/////////////////////////////////////////////////////////////////////////////////////////
//
// DEPRECATED
@@ -2667,274 +321,58 @@
}
/****************************************************************************************
- * @builtin SourceMoveDownloadArea
+ * @builtin SourceInstallOrder
*
- * @short Move download area of CURL-based sources to specified directory
- * @param path specifies the path to move the download area to
+ * @short not implemented, do not use (Explicitly set an install order.)
* @return boolean
**/
YCPValue
-PkgModuleFunctions::SourceMoveDownloadArea (const YCPString & path)
-{
- try
- {
- y2milestone("Moving download area of all sources to %s", path->value().c_str());
- zypp::media::MediaManager manager;
- manager.setAttachPrefix(path->value());
- }
- catch (zypp::Exception & excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error("Pkg::SourceMoveDownloadArea has failed: %s", excpt.msg().c_str());
- return YCPBoolean(false);
- }
-
- y2milestone( "Download areas moved");
-
- return YCPBoolean(true);
-}
-
-/*
- * A helper function - remove all resolvables from the repository from the pool
- */
-void PkgModuleFunctions::RemoveResolvablesFrom(const std::string &alias)
-{
- // remove the resolvables if they have been loaded
- // FIXME: can be implemented better? we need a ResStore object for removing,
- // which means search for a resolvable in the pool and get the Repository
- // object which can be asked for all resolvables in it
- for (zypp::ResPool::const_iterator it = zypp_ptr()->pool().begin()
- ; it != zypp_ptr()->pool().end()
- ; ++it)
- {
- if (it->resolvable()->repository().info().alias() == alias)
- {
- y2milestone("Removing all resolvables from '%s' from the pool...", alias.c_str());
- zypp_ptr()->removeResolvables(it->resolvable()->repository().resolvables());
- break;
- }
- }
-}
-
-/*
- * A helper function - is there any resolvable from the repository in the pool?
- */
-bool PkgModuleFunctions::AnyResolvableFrom(const std::string &alias)
+PkgModuleFunctions::SourceInstallOrder (const YCPMap& ord)
{
- for (zypp::ResPool::const_iterator it = zypp_ptr()->pool().begin()
- ; it != zypp_ptr()->pool().end()
- ; ++it)
- {
- if (it->resolvable()->repository().info().alias() == alias)
- {
- return true;
- }
- }
-
- return false;
+#warning SourceInstallOrder is not implemented
+ return YCPBoolean( true );
}
-/*
- * A helper function - load resolvable from the repository into the pool
- * Warning: Use AnyResolvableFrom() method for checing if the resolvables might be already loaded
- */
-bool PkgModuleFunctions::LoadResolvablesFrom(const zypp::RepoInfo &repoinfo)
-{
- bool success = true;
- unsigned int size_start = zypp_ptr()->pool().size();
- y2milestone("Loading resolvables from '%s', pool size at start: %d", repoinfo.alias().c_str(), size_start);
-
- try
- {
- zypp::RepoManager repomanager = CreateRepoManager();
-
- // build cache if needed
- if (!repomanager.isCached(repoinfo))
- {
- zypp::RepoStatus raw_metadata_status = repomanager.metadataStatus(repoinfo);
- if (raw_metadata_status.empty())
- {
- y2milestone("Missing metadata for source '%s', downloading...", repoinfo.alias().c_str());
- RefreshWithCallbacks(repoinfo);
- }
-
- y2milestone("Caching source '%s'...", repoinfo.alias().c_str());
- repomanager.buildCache(repoinfo);
- }
-
- zypp::Repository repository = repomanager.createFromCache(repoinfo);
- const zypp::ResStore &store = repository.resolvables();
-
- // load resolvables
- zypp_ptr()->addResolvables(store);
-
- y2milestone("Loaded %zd resolvables", store.size());
- }
- catch(const zypp::repo::RepoNotCachedException &excpt )
- {
- std::string alias = repoinfo.alias();
- y2error ("Resolvables from '%s' havn't been loaded: %s", alias.c_str(), excpt.asString().c_str());
- _last_error.setLastError("'" + alias + "': " + ExceptionAsString(excpt));
- success = false;
-
- // FIXME ??
- /*
- // disable the source
- y2error("Disabling source %s", url.c_str());
- repo->disable();
- */
- }
- catch (const zypp::Exception& excpt)
- {
- std::string alias = repoinfo.alias();
- y2internal("Error: Loading resolvables failed: %s", ExceptionAsString(excpt).c_str());
- _last_error.setLastError("'" + alias + "': " + ExceptionAsString(excpt));
- success = false;
- }
-
- unsigned int size_end = zypp_ptr()->pool().size();
- y2milestone("Pool size at end: %d (loaded %d resolvables)", size_end, size_end - size_start);
- return success;
-}
/****************************************************************************************
- * @builtin RepositoryProbe
+ * @builtin SourceDelete
+ * @short Delete a Source
+ * @description
+ * Delete an InsrSrc. The InsrSrc together with all metadata cached on disk
+ * is removed. The SrcId passed becomes invalid (other SrcIds stay valid).
*
- * @short Probe type of the repository
- * @param url specifies the path to the repository
- * @param prod_dir product directory (if empty the url is probed directly)
- * @return string repository type ("NONE" if type could be determined, nil if an error occurred (e.g. resolving the hostname)
- **/
-YCPValue PkgModuleFunctions::RepositoryProbe(const YCPString& url, const YCPString& prod_dir)
-{
- y2milestone("Probing repository type: '%s'...", url->value().c_str());
- zypp::RepoManager repomanager = CreateRepoManager();
- std::string ret;
-
- try
- {
- zypp::Url probe_url(url->value());
-
- // add the product directory
- std::string prod = prod_dir->value();
-
- if (!prod.empty())
- {
- // add "/" at the begining if it's missing
- if (std::string(prod, 0, 1) != "/")
- {
- prod = "/" + prod;
- }
-
- // merge the URL path and the product path
- std::string path = probe_url.getPathName();
- path += prod;
-
- y2milestone("Using probing path: %s", path.c_str());
- probe_url.setPathName(path);
- }
-
- // add "ro" mount option
- probe_url = addRO(probe_url);
-
- // autoprobe type of the repository
- zypp::repo::RepoType repotype = ProbeWithCallbacks(probe_url);
-
- ret = zypp2yastType(repotype.asString());
- y2milestone("Detected type: '%s'...", ret.c_str());
- }
- catch (const zypp::Exception& excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error( "Cannot detect the repository type" );
- return YCPVoid();
- }
-
- return YCPString(ret);
-}
-
-/****************************************************************************************
- * @builtin RepositoryScan
+ * @param integer SrcId Specifies the InstSrc.
*
- * @short Scan available products in the repository
- * @param url specifies the path to the repository
- * @return list<list<string>> list of the products: [ [ <product_name_1> <directory_1> ], ...]
+ * @return boolean
**/
-YCPValue PkgModuleFunctions::RepositoryScan(const YCPString& url)
+YCPValue
+PkgModuleFunctions::SourceDelete (const YCPInteger& id)
{
- zypp::MediaProductSet products;
-
- try
- {
- zypp::Url baseurl(url->value());
-
- baseurl = addRO(baseurl);
-
- ScanProductsWithCallBacks(baseurl);
- products = available_products;
- }
- catch ( const zypp::Exception& excpt)
- {
- _last_error.setLastError(ExceptionAsString(excpt));
- y2error( "Cannot read the product list from the media" );
- return YCPList();
- }
-
- YCPList ret;
-
- for( zypp::MediaProductSet::const_iterator it = products.begin();
- it != products.end() ; ++it )
- {
- YCPList prod;
-
- // add product directory
- prod.add(YCPString(it->_name));
- // add product name
- prod.add(YCPString(it->_dir.asString()));
-
- ret.add(prod);
- }
-
- y2milestone("Found products: %s", ret->toString().c_str());
-
- return ret;
-}
+ YRepo_Ptr repo = logFindRepository(id->value());
+ if (!repo)
+ return YCPBoolean(false);
-// convert libzypp type to yast strings ("YaST", "YUM" or "Plaindir")
-std::string PkgModuleFunctions::zypp2yastType(const std::string &type)
-{
- std::string ret(type);
+ bool success = true;
- if (type_conversion_table.empty())
+ try
{
- // initialize the conversion map
- type_conversion_table["rpm-md"] = "YUM";
- type_conversion_table["yast2"] = "YaST";
- type_conversion_table["plaindir"] = "Plaindir";
- type_conversion_table["NONE"] = "NONE";
- }
+ // the resolvables cannot be used anymore, remove them
+ RemoveResolvablesFrom(repo->repoInfo().alias());
- std::map<std::string,std::string>::const_iterator it = type_conversion_table.find(type);
+ // update 'repos'
+ repo->setDeleted();
- // found in the conversion table
- if (it != type_conversion_table.end())
- {
- ret = it->second;
+ PkgFreshen();
}
- else
+ catch (const zypp::Exception& excpt)
{
- y2error("Cannot convert type '%s'", type.c_str());
+ std::string alias = repo->repoInfo().alias();
+ y2error ("Error for '%s': %s", alias.c_str(), excpt.asString().c_str());
+ _last_error.setLastError(alias + ": " + ExceptionAsString(excpt));
+ success = false;
}
- return ret;
+ return YCPBoolean(success);
}
-std::string PkgModuleFunctions::yast2zyppType(const std::string &type)
-{
- // do conversion from the Yast type ("YaST", "YUM", "Plaindir")
- // to libzypp type ("yast", "yum", "plaindir")
- // we can simply use toLower instead of a conversion table
- // in this case
- return zypp::str::toLower(type);
-}
Copied: trunk/pkg-bindings/src/Y2PkgFunction.cc (from r42212, trunk/pkg-bindings/src/PkgModuleFunctions.cc)
URL: http://svn.opensuse.org/viewcvs/yast/trunk/pkg-bindings/src/Y2PkgFunction.c…
==============================================================================
--- trunk/pkg-bindings/src/PkgModuleFunctions.cc (original)
+++ trunk/pkg-bindings/src/Y2PkgFunction.cc Thu Dec 6 07:56:58 2007
@@ -21,54 +21,7 @@
/-*/
-#include <ycp/YExpression.h>
-#include <ycp/YBlock.h>
-#include "PkgModuleFunctions.h"
-
-#include "Callbacks.h"
-
-#include <ycp/YCPInteger.h>
-#include <ycp/YCPString.h>
-#include <ycp/YCPBoolean.h>
-#include <ycp/YCPMap.h>
-#include <ycp/YCPVoid.h>
-
-#include <zypp/ZYppFactory.h>
-#include <zypp/ResPool.h>
-#include <zypp/RepoInfo.h>
-#include <zypp/MediaSetAccess.h>
-
-// sleep
-#include <unistd.h>
-
-// exit
-#include <cstdlib>
-
-// textdomain
-#include <libintl.h>
-
-class Y2PkgFunction: public Y2Function
-{
- unsigned int m_position;
- PkgModuleFunctions* m_instance;
- YCPValue m_param1;
- YCPValue m_param2;
- YCPValue m_param3;
- YCPValue m_param4;
- YCPValue m_param5;
- string m_name;
-public:
-
- Y2PkgFunction (string name, PkgModuleFunctions* instance, unsigned int pos);
- bool attachParameter (const YCPValue& arg, const int position);
- constTypePtr wantedParameterType () const;
- bool appendParameter (const YCPValue& arg);
- bool finishParameters ();
- YCPValue evaluateCall ();
- bool reset ();
- string name () const;
-};
-
+#include "Y2PkgFunction.h"
Y2PkgFunction::Y2PkgFunction (string name, PkgModuleFunctions* instance, unsigned int pos) :
m_position (pos)
@@ -174,543 +127,3 @@
{
return m_name;
}
-
-/////////////////////////////////////////////////////////////////////////////
-//
-// Class: YRepo
-//
-
-IMPL_PTR_TYPE(YRepo);
-
-YRepo::YRepo(zypp::RepoInfo & repo)
- : _repo(repo), _deleted(false)
-{}
-
-YRepo::~YRepo()
-{
- if (_maccess)
- {
- try { _maccess->release(); }
- catch (const zypp::media::MediaException & ex)
- {
- y2error("Error in ~Yrepo(): %s", ex.asString().c_str());
- }
- }
-}
-
-zypp::MediaSetAccess_Ptr & YRepo::mediaAccess()
-{
- if (!_maccess)
- {
- y2milestone("Creating new MediaSetAccess for url %s",
- (*_repo.baseUrlsBegin()).asString().c_str());
- _maccess = new zypp::MediaSetAccess(*_repo.baseUrlsBegin()); // FIXME handle multiple baseUrls
- }
-
- return _maccess;
-}
-
-const YRepo YRepo::NOREPO;
-
-/////////////////////////////////////////////////////////////////////////////
-
-
-const zypp::ResStatus::TransactByValue PkgModuleFunctions::whoWantsIt = zypp::ResStatus::APPL_HIGH;
-
-/**
- * Constructor.
- */
-PkgModuleFunctions::PkgModuleFunctions ()
- : Y2Namespace()
- , _target_root( "/" )
- , zypp_pointer(NULL)
- ,_callbackHandler( *new CallbackHandler(*this) )
-{
- registerFunctions ();
-
- const char *domain = "pkg-bindings";
- bindtextdomain( domain, LOCALEDIR );
- bind_textdomain_codeset( domain, "utf8" );
- textdomain( domain );
-
- // Make change known.
- {
- extern int _nl_msg_cat_cntr;
- ++_nl_msg_cat_cntr;
- }
-}
-
-/**
- * Connect to Zypp library if it is not already connected.
- */
-zypp::ZYpp::Ptr PkgModuleFunctions::zypp_ptr()
-{
- if (zypp_pointer != NULL)
- {
- return zypp_pointer;
- }
-
- int max_count = 5;
- unsigned int seconds = 3;
-
- while (zypp_pointer == NULL && max_count > 0)
- {
- try
- {
- y2milestone("Initializing Zypp library...");
- zypp_pointer = zypp::getZYpp();
- return zypp_pointer;
- }
- catch (...)
- {
- }
-
- max_count--;
-
- if (zypp_pointer == NULL && max_count > 0)
- {
- sleep(seconds);
- }
- }
-
- // still not initialized, throw an exception
- ZYPP_THROW (zypp::Exception(std::string("Cannot connect to the package manager")));
-
- return zypp_pointer;
-}
-
-
-/**
- * Destructor.
- */
-PkgModuleFunctions::~PkgModuleFunctions ()
-{
- delete &_callbackHandler;
-
- if (zypp_pointer != NULL)
- {
- try
- {
- y2milestone("Finishing the target");
- zypp_pointer->finishTarget();
- }
- catch(...)
- {
- y2error("finishTarget() has failed");
- }
-
- y2milestone("Releasing the zypp pointer...");
- zypp_pointer = NULL;
- y2milestone("Zypp pointer released");
- }
-}
-
-Y2Function* PkgModuleFunctions::createFunctionCall (const string name, constFunctionTypePtr type)
-{
- vector<string>::iterator it = find (_registered_functions.begin ()
- , _registered_functions.end (), name);
- if (it == _registered_functions.end ())
- {
- y2error ("No such function %s", name.c_str ());
- return NULL;
- }
-
- return new Y2PkgFunction (name, this, it - _registered_functions.begin ());
-}
-
-void PkgModuleFunctions::registerFunctions()
-{
-#include "PkgBuiltinTable.h"
-}
-
-
-// ------------------------------------------------------------------
-// general
-
-/**
- * @builtin Connect
- * @short Explicitly connect to the package manager, if it is already connected do nothing
- * @description Checks whether the package manager is connected to Yast,
- * if not try connecting to it.
- * @return boolean true if the package manager is connected
- */
-YCPValue
-PkgModuleFunctions::Connect()
-{
- try
- {
- return YCPBoolean(zypp_ptr() != NULL);
- }
- catch(...)
- {
- }
-
- return YCPBoolean(false);
-}
-
-/**
- * @builtin InstSysMode
- * @short obsoleted - do not use
- * @return void
- */
-YCPValue
-PkgModuleFunctions::InstSysMode ()
-{
- y2warning("Pkg::InstSysMode() is obsoleted, it's not needed anymore");
- return YCPVoid();
-}
-
-/**
- * @builtin SetTextLocale
- * @short Set Package Manager Locale
- * @description
- * Set the given locale as the output locale -- all messages from the package manager (errors, warnings,...)
- * will be returned in the selected language. This built-in does not change package selection in any way.
- * @param string locale Locale
- * @return void
- */
-YCPValue
-PkgModuleFunctions::SetTextLocale (const YCPString &locale)
-{
- try
- {
- zypp::Locale loc = zypp::Locale(locale->value());
- zypp_ptr()->setTextLocale(loc);
- }
- catch (const std::exception& excpt)
- {
- y2error("Caught an exception: %s", excpt.what());
- }
- catch (...)
- {
- y2internal("Caught an unknown exception");
- }
-
- return YCPVoid();
-}
-
-/**
- * @builtin SetPackageLocale
- * @short Select locale for installation
- * @description
- * Select the main locale for installation, call Pkg::PkgSolve() to select the respective packages.
- * @param string locale Locale
- * @return void
- */
-YCPValue
-PkgModuleFunctions::SetPackageLocale (const YCPString &locale)
-{
- try
- {
- zypp::Locale loc = zypp::Locale(locale->value());
-
- // add packages for the preferred locale, preserve additional locales
- zypp::ZYpp::LocaleSet lset = zypp_ptr()->getRequestedLocales();
-
- // remove the previous locale
- if (preferred_locale != zypp::Locale::noCode)
- {
- lset.erase(preferred_locale);
- }
-
- // add the new locale
- lset.insert(loc);
- zypp_ptr()->setRequestedLocales(lset);
-
- // remember the main locale
- preferred_locale = loc;
- }
- catch(...)
- {
- }
-
- return YCPVoid();
-}
-
-/**
- * @builtin SetLocale
- * @short Set The Main (Preferred) Locale -- OBSOLETED!
- * @description
- * OBSOLETED, DO NOT USE! It has been replaced by SetTextLocale() and SetMainLocale() calls (see bug #223624)
- * @param string locale Locale
- * @return void
- */
-YCPValue
-PkgModuleFunctions::SetLocale (const YCPString &locale)
-{
- y2warning("Pkg::SetLocale() is obsoleted, use Pkg::SetTextLocale() and/or Pkg::SetPackageLocale() instead. Pkg::SetLocale() currently calls both functions");
-
- SetTextLocale(locale);
- SetPackageLocale(locale);
-
- return YCPVoid();
-}
-
-/**
- * @builtin GetTextLocale
- * @short get the currently preferred locale
- * @return string locale
- * @usage Pkg::GetTextLocale() -> "en_US"
- */
-YCPValue
-PkgModuleFunctions::GetTextLocale ()
-{
- try
- {
- return YCPString(zypp_ptr()->getTextLocale().code());
- }
- catch (...)
- {
- }
-
- return YCPVoid();
-}
-
-/**
- * @builtin GetLocale
- * @short get the currently preferred locale
- * @return string locale
- * @usage Pkg::GetLocale () -> "en_US"
- */
-YCPValue
-PkgModuleFunctions::GetLocale ()
-{
- y2warning("Pkg::GetLocale() is obsoleted, use Pkg::GetTextLocale() or Pkg::GetPackageLocale() instead. Pkg::GetLocale() currently calls Pkg::GetTextLocale()");
- return GetTextLocale();
-}
-
-/**
- * @builtin GetPackageLocale
- * @short get the locale set by Pkg::SetPackageLocale() call
- * @return string locale
- * @usage Pkg::GetPackageLocale () -> "en_US"
- */
-YCPValue
-PkgModuleFunctions::GetPackageLocale ()
-{
- // the locale hasn't been initialized
- if (preferred_locale == zypp::Locale::noCode)
- {
- y2warning("The package locale hasn't been set, call Pkg::SetPackageLocale() before Pkg::GetPackageLocale()");
- }
-
- return YCPString(preferred_locale.code());
-}
-
-/**
- * @builtin SetAdditionalLocales
- *
- * @short set list of additional locales
- * @description
- * Select additional languages for installation. Call Pkg::Solve() to select the respective packages.
- * @param list<string> locales List of additional locales
- * @return void
- * @usage Pkg::SetAdditionalLocales(["de_DE"]);
- */
-YCPValue
-PkgModuleFunctions::SetAdditionalLocales (YCPList langycplist)
-{
- zypp::ZYpp::LocaleSet lset;
-
- int i = 0;
- while (i < langycplist->size())
- {
- if (langycplist->value(i)->isString())
- {
- lset.insert(zypp::Locale(langycplist->value(i)->asString()->value()));
- }
- else
- {
- y2error("Pkg::SetAdditionalLocales ([...,%s,...]) not string", langycplist->value(i)->toString().c_str());
- }
- i++;
- }
-
- // add the main locale if it's initialized
- if (preferred_locale != zypp::Locale::noCode)
- {
- lset.insert(preferred_locale);
- }
-
- try
- {
- zypp_ptr()->setRequestedLocales(lset);
- }
- catch(...)
- {
- }
-
- return YCPVoid();
-}
-
-/**
- * @builtin GetAdditionalLocales
- *
- * @short return list of additional locales
- * @return list<string>
- * @usage Pkg::GetAdditionalLocales() -> ["de_DE"];
- *
- */
-YCPValue
-PkgModuleFunctions::GetAdditionalLocales ()
-{
- YCPList langycplist;
-
- try
- {
- zypp::ZYpp::LocaleSet lset = zypp_ptr()->getRequestedLocales();
-
- for (zypp::ZYpp::LocaleSet::const_iterator it = lset.begin();
- it != lset.end(); ++it)
- {
- // ignore the main locale
- if (*it != preferred_locale)
- {
- langycplist->add (YCPString(it->code()));
- }
- }
- }
- catch(...)
- {
- }
-
- return langycplist;
-}
-
-
-/**
- * @builtin LastError
- *
- * @short get current error as string
- * @return string
- */
-YCPValue
-PkgModuleFunctions::LastError ()
-{
- return YCPString(_last_error.lastError());
-}
-
-/**
- * @builtin LastErrorDetails
- *
- * @short get current error details as string
- * @return string Error Details
- */
-YCPValue
-PkgModuleFunctions::LastErrorDetails ()
-{
- return YCPString (_last_error.lastErrorDetails());
-}
-
-/**
- * @builtin LastErrorId
- * @short Obsoleted function, do not use
- * @return string
- */
-YCPValue
-PkgModuleFunctions::LastErrorId ()
-{
-
- /* TODO FIXME
- int errorId = _last_error;
- switch ( errorId ) {
- case PMError::E_ok:
- return YCPString( "ok" );
- case InstSrcError::E_isrc_cache_duplicate:
- return YCPString( "instsrc_duplicate" );
- default:
- return YCPString( "error" );
- }
- */
-
- return YCPString( "ok" );
-}
-
-/**
- * @builtin Init
- * @short completely initialize package management (currently it is empty)
- * @return boolean true on success
- */
-YCPValue
-PkgModuleFunctions::Init ()
-{
-#warning FIXME can be Init() empty??
- return YCPBoolean(true);
-}
-
-zypp::RepoManager PkgModuleFunctions::CreateRepoManager()
-{
- // set path option, use root dir as a prefix for the default directory
- zypp::RepoManagerOptions repo_options;
- repo_options.knownReposPath = zypp::Pathname(_target_root) + repo_options.knownReposPath;
-
- y2milestone("Path to repository files: %s", repo_options.knownReposPath.asString().c_str());
-
- return zypp::RepoManager(repo_options);
-}
-
-// convert Exception object to string represenatation
-std::string PkgModuleFunctions::ExceptionAsString(const zypp::Exception &e)
-{
- std::string ret = e.asUserString();
-
- if (e.historySize() > 0)
- {
- ret += "\n" + e.historyAsString();
- }
-
- y2debug("Error message: %s", ret.c_str());
-
- return ret;
-}
-
-
-/** ------------------------
- * Convert InstSrcDescr to product info YCPMap:
- * <TABLE>
- * <TR><TD>$[<TD>"product" <TD>: YCPString (name' 'version)
- * <TR><TD>,<TD>"vendor" <TD>: YCPString
- * <TR><TD>,<TD>"requires" <TD>: YCPString
- * <TR><TD>,<TD>"name" <TD>: YCPString
- * <TR><TD>,<TD>"version" <TD>: YCPString
- * <TR><TD>,<TD>"flags" <TD>: YCPString
- * <TR><TD>,<TD>"relnotesurl" <TD>: YCPString
- * <TR><TD>,<TD>"distproduct" <TD>: YCPString
- * <TR><TD>,<TD>"distversion" <TD>: YCPString
- * <TR><TD>,<TD>"baseproduct" <TD>: YCPString
- * <TR><TD>,<TD>"baseversion" <TD>: YCPString
- * <TR><TD>];
- * </TABLE>
-
-
-YCPMap
-PkgModuleFunctions::Descr2Map (constInstSrcDescrPtr descr)
-{
- YCPMap map;
-
- map->add (YCPString ("product"), YCPString (descr->content_product().asPkgNameEd().name.asString()
- + " "
- + descr->content_product().asPkgNameEd().edition.version()));
- map->add (YCPString ("vendor"), YCPString (descr->content_vendor()));
- map->add (YCPString ("requires"), YCPString (descr->content_requires().asString()));
-
- // for installation/modules/Product.ycp
- map->add (YCPString ("name"), YCPString (descr->content_product().asPkgNameEd().name));
- map->add (YCPString ("version"), YCPString (descr->content_product().asPkgNameEd().edition.version()));
- map->add (YCPString ("flags"), YCPString (descr->content_flags()));
- map->add (YCPString ("relnotesurl"), YCPString (descr->content_relnotesurl()));
-
- // vendor already in map
-
- map->add (YCPString ("distproduct"), YCPString (descr->content_distproduct().name));
- map->add (YCPString ("distversion"), YCPString (descr->content_distproduct().edition.version()));
-
- map->add (YCPString ("baseproduct"), YCPString (descr->content_baseproduct().asPkgNameEd().name));
- map->add (YCPString ("baseversion"), YCPString (descr->content_baseproduct().asPkgNameEd().edition.version()));
-
- map->add (YCPString ("defaultbase"), YCPString (descr->content_defaultbase()));
-
- return map;
-}
-*/
-
Added: trunk/pkg-bindings/src/Y2PkgFunction.h
URL: http://svn.opensuse.org/viewcvs/yast/trunk/pkg-bindings/src/Y2PkgFunction.h…
==============================================================================
--- trunk/pkg-bindings/src/Y2PkgFunction.h (added)
+++ trunk/pkg-bindings/src/Y2PkgFunction.h Thu Dec 6 07:56:58 2007
@@ -0,0 +1,32 @@
+
+#ifndef Y2PkgFunction_h
+#define Y2PkgFunction_h
+
+#include "PkgModuleFunctions.h"
+
+#include <y2/Y2Function.h>
+
+class Y2PkgFunction: public Y2Function
+{
+ unsigned int m_position;
+ PkgModuleFunctions* m_instance;
+ YCPValue m_param1;
+ YCPValue m_param2;
+ YCPValue m_param3;
+ YCPValue m_param4;
+ YCPValue m_param5;
+ string m_name;
+public:
+
+ Y2PkgFunction (string name, PkgModuleFunctions* instance, unsigned int pos);
+ bool attachParameter (const YCPValue& arg, const int position);
+ constTypePtr wantedParameterType () const;
+ bool appendParameter (const YCPValue& arg);
+ bool finishParameters ();
+ YCPValue evaluateCall ();
+ bool reset ();
+ string name () const;
+};
+
+#endif
+
Added: trunk/pkg-bindings/src/YRepo.cc
URL: http://svn.opensuse.org/viewcvs/yast/trunk/pkg-bindings/src/YRepo.cc?rev=42…
==============================================================================
--- trunk/pkg-bindings/src/YRepo.cc (added)
+++ trunk/pkg-bindings/src/YRepo.cc Thu Dec 6 07:56:58 2007
@@ -0,0 +1,43 @@
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// Class: YRepo
+//
+
+#include <YRepo.h>
+
+#define y2log_component "Pkg"
+#include <ycp/y2log.h>
+
+IMPL_PTR_TYPE(YRepo);
+
+YRepo::YRepo(zypp::RepoInfo & repo)
+ : _repo(repo), _deleted(false)
+{}
+
+YRepo::~YRepo()
+{
+ if (_maccess)
+ {
+ try { _maccess->release(); }
+ catch (const zypp::media::MediaException & ex)
+ {
+ y2error("Error in ~Yrepo(): %s", ex.asString().c_str());
+ }
+ }
+}
+
+zypp::MediaSetAccess_Ptr & YRepo::mediaAccess()
+{
+ if (!_maccess)
+ {
+ y2milestone("Creating new MediaSetAccess for url %s",
+ (*_repo.baseUrlsBegin()).asString().c_str());
+ _maccess = new zypp::MediaSetAccess(*_repo.baseUrlsBegin()); // FIXME handle multiple baseUrls
+ }
+
+ return _maccess;
+}
+
+const YRepo YRepo::NOREPO;
+
Added: trunk/pkg-bindings/src/YRepo.h
URL: http://svn.opensuse.org/viewcvs/yast/trunk/pkg-bindings/src/YRepo.h?rev=427…
==============================================================================
--- trunk/pkg-bindings/src/YRepo.h (added)
+++ trunk/pkg-bindings/src/YRepo.h Thu Dec 6 07:56:58 2007
@@ -0,0 +1,34 @@
+
+#ifndef YRepo_h
+#define YRepo_h
+
+#include <zypp/RepoInfo.h>
+#include <zypp/MediaSetAccess.h>
+#include <zypp/base/ReferenceCounted.h>
+
+DEFINE_PTR_TYPE(YRepo);
+class YRepo : public zypp::base::ReferenceCounted
+{
+private:
+ zypp::RepoInfo _repo;
+ zypp::MediaSetAccess_Ptr _maccess;
+ bool _deleted;
+
+ YRepo() {}
+
+public:
+ YRepo(zypp::RepoInfo & repo);
+ ~YRepo();
+
+ const zypp::RepoInfo & repoInfo() const { return _repo; }
+ zypp::RepoInfo & repoInfo() { return _repo; }
+ zypp::MediaSetAccess_Ptr & mediaAccess();
+
+ bool isDeleted() {return _deleted;}
+ void setDeleted() {_deleted = true;}
+
+public:
+ static const YRepo NOREPO;
+};
+
+#endif
--
To unsubscribe, e-mail: yast-commit+unsubscribe(a)opensuse.org
For additional commands, e-mail: yast-commit+help(a)opensuse.org
1
0