1
0
mirror of https://github.com/openSUSE/osc.git synced 2025-01-12 08:56:13 +01:00

code cleanup

This commit is contained in:
Pavol Rusnak 2009-10-20 14:30:15 +00:00
parent ce0c2a5ad2
commit 661d927d38
18 changed files with 756 additions and 764 deletions

332
dist/osc.complete vendored
View File

@ -63,320 +63,320 @@ submit ()
local target local target
if ((pos == 1)) ; then if ((pos == 1)) ; then
if test -z "${cmdline[$((2+off))]}" -a -n "${oscprj}" ; then if test -z "${cmdline[$((2+off))]}" -a -n "${oscprj}" ; then
builtin compgen -W "${oscprj}" builtin compgen -W "${oscprj}"
else else
builtin compgen -W "$(command cat ~/.osc.projects)" -- "${cmdline[$((2+off))]}" builtin compgen -W "$(command cat ~/.osc.projects)" -- "${cmdline[$((2+off))]}"
fi fi
fi fi
if ((pos == 2)) ; then if ((pos == 2)) ; then
if test -z "${cmdline[$((3+off))]}" -a -n "${oscpkg}" ; then if test -z "${cmdline[$((3+off))]}" -a -n "${oscpkg}" ; then
builtin compgen -W "${oscpkg}" builtin compgen -W "${oscpkg}"
else else
builtin compgen -W "$(command osc ls "${cmdline[$((2+off))]}")" -- "${cmdline[$((3+off))]}" builtin compgen -W "$(command osc ls "${cmdline[$((2+off))]}")" -- "${cmdline[$((3+off))]}"
fi fi
fi fi
if ((pos == 3)) ; then if ((pos == 3)) ; then
if test -z "${cmdline[$((4+off))]}" -a -n "${lnkprj}" ; then if test -z "${cmdline[$((4+off))]}" -a -n "${lnkprj}" ; then
builtin compgen -W "${lnkprj}" builtin compgen -W "${lnkprj}"
else else
builtin compgen -W "$(command cat ~/.osc.projects)" -- "${cmdline[$((4+off))]}" builtin compgen -W "$(command cat ~/.osc.projects)" -- "${cmdline[$((4+off))]}"
fi fi
fi fi
if ((pos == 4)) ; then if ((pos == 4)) ; then
target="${lnkpkg}" target="${lnkpkg}"
target="${target:+$target }$oscpkg" target="${target:+$target }$oscpkg"
if test -n "${target}" ; then if test -n "${target}" ; then
builtin compgen -W "${target}" -- "${cmdline[$((5+off))]}" builtin compgen -W "${target}" -- "${cmdline[$((5+off))]}"
else else
builtin compgen -W "$(command osc ls "${cmdline[$((4+off))]}")" -- "${cmdline[$((5+off))]}" builtin compgen -W "$(command osc ls "${cmdline[$((4+off))]}")" -- "${cmdline[$((5+off))]}"
fi fi
fi fi
} }
case "${cmdline[1]}" in case "${cmdline[1]}" in
add|addremove|ar) add|addremove|ar)
if ((count == 1)) ; then if ((count == 1)) ; then
builtin compgen -W 'add addremove ar' -- "${cmdline[1]}" builtin compgen -W 'add addremove ar' -- "${cmdline[1]}"
else else
for x in $(builtin compgen -f -X '.osc' -- "${cmdline[2]}"); do for x in $(builtin compgen -f -X '.osc' -- "${cmdline[2]}"); do
test -d $x && builtin echo $x/ || builtin echo $x test -d $x && builtin echo $x/ || builtin echo $x
done done
fi fi
;; ;;
branch) branch)
if ((count == 1)) ; then if ((count == 1)) ; then
builtin compgen -W 'branch' -- "${cmdline[1]}" builtin compgen -W 'branch' -- "${cmdline[1]}"
fi fi
case "${cmdline[2]}" in case "${cmdline[2]}" in
--nodevelproject) --nodevelproject)
if ((count == 3)) ; then if ((count == 3)) ; then
builtin compgen -W "$(command cat ~/.osc.projects)" -- "${cmdline[3]}" builtin compgen -W "$(command cat ~/.osc.projects)" -- "${cmdline[3]}"
fi fi
if ((count == 4)) ; then if ((count == 4)) ; then
builtin compgen -W "$(command osc ls "${cmdline[3]}")" -- "${cmdline[4]}" builtin compgen -W "$(command osc ls "${cmdline[3]}")" -- "${cmdline[4]}"
fi fi
;; ;;
-*) builtin compgen -W '--nodevelproject' -- "${cmdline[3]}" ;; -*) builtin compgen -W '--nodevelproject' -- "${cmdline[3]}" ;;
*) *)
if ((count == 2)) ; then if ((count == 2)) ; then
builtin compgen -W "$(command cat ~/.osc.projects)" -- "${cmdline[2]}" builtin compgen -W "$(command cat ~/.osc.projects)" -- "${cmdline[2]}"
fi fi
if ((count == 3)) ; then if ((count == 3)) ; then
builtin compgen -W "$(command osc ls "${cmdline[2]}")" -- "${cmdline[3]}" builtin compgen -W "$(command osc ls "${cmdline[2]}")" -- "${cmdline[3]}"
fi fi
esac esac
;; ;;
list|ls) list|ls)
if ((count == 1)) ; then if ((count == 1)) ; then
builtin compgen -W 'list ls' -- "${cmdline[1]}" builtin compgen -W 'list ls' -- "${cmdline[1]}"
fi fi
if ((count == 2)) ; then if ((count == 2)) ; then
builtin compgen -W "$(command cat ~/.osc.projects)" -- "${cmdline[2]}" builtin compgen -W "$(command cat ~/.osc.projects)" -- "${cmdline[2]}"
fi fi
if ((count == 3)) ; then if ((count == 3)) ; then
builtin compgen -W "$(command osc ls "${cmdline[2]}")" -- "${cmdline[3]}" builtin compgen -W "$(command osc ls "${cmdline[2]}")" -- "${cmdline[3]}"
fi fi
;; ;;
sr|submitreq|submitrequest) sr|submitreq|submitrequest)
if ((count == 1)) ; then if ((count == 1)) ; then
builtin compgen -W 'sr submitreq submitrequest' -- "${cmdline[1]}" builtin compgen -W 'sr submitreq submitrequest' -- "${cmdline[1]}"
fi fi
case "${cmdline[2]}" in case "${cmdline[2]}" in
--nodevelproject) --nodevelproject)
submit $((count - 2)) 1 ;; submit $((count - 2)) 1 ;;
-*) builtin compgen -W '--nodevelproject' -- "${cmdline[2]}" ;; -*) builtin compgen -W '--nodevelproject' -- "${cmdline[2]}" ;;
*) submit $((count - 1)) 0 ;; *) submit $((count - 1)) 0 ;;
esac esac
;; ;;
rq|request) rq|request)
if ((count == 1)) ; then if ((count == 1)) ; then
builtin compgen -W 'rq request' -- "${cmdline[1]}" builtin compgen -W 'rq request' -- "${cmdline[1]}"
fi fi
case "${cmdline[2]}" in case "${cmdline[2]}" in
accept|decline|wipe|revoke|log) accept|decline|wipe|revoke|log)
if ((count == 3)) ; then if ((count == 3)) ; then
builtin echo -n 'ID' builtin echo -n 'ID'
fi fi
;; ;;
show) show)
if ((count == 3)) ; then if ((count == 3)) ; then
builtin compgen -W '--diff' -- "${cmdline[3]}" builtin compgen -W '--diff' -- "${cmdline[3]}"
else else
builtin echo -n 'ID' builtin echo -n 'ID'
fi fi
;; ;;
list) list)
if ((count == 3)) ; then if ((count == 3)) ; then
builtin compgen -W "$(command cat ~/.osc.projects)" -- "${cmdline[3]}" builtin compgen -W "$(command cat ~/.osc.projects)" -- "${cmdline[3]}"
fi fi
if ((count == 4)) ; then if ((count == 4)) ; then
builtin compgen -W "$(command osc ls "${cmdline[3]}")" -- "${cmdline[4]}" builtin compgen -W "$(command osc ls "${cmdline[3]}")" -- "${cmdline[4]}"
fi fi
;; ;;
*) *)
((count == 2)) && builtin compgen -W "$(builtin echo ${oscreq[@]})" -- "${cmdline[2]}" ((count == 2)) && builtin compgen -W "$(builtin echo ${oscreq[@]})" -- "${cmdline[2]}"
esac esac
;; ;;
copypac|linkpac) copypac|linkpac)
if ((count == 1)) ; then if ((count == 1)) ; then
builtin compgen -W 'copypac linkpac' -- "${cmdline[1]}" builtin compgen -W 'copypac linkpac' -- "${cmdline[1]}"
fi fi
case "${cmdline[2]}" in case "${cmdline[2]}" in
*) *)
if ((count == 2)) ; then if ((count == 2)) ; then
builtin compgen -W "$(command cat ~/.osc.projects)" -- "${cmdline[2]}" builtin compgen -W "$(command cat ~/.osc.projects)" -- "${cmdline[2]}"
fi fi
if ((count == 3)) ; then if ((count == 3)) ; then
builtin compgen -W "$(osc ls "${cmdline[2]}")" -- "${cmdline[3]}" builtin compgen -W "$(osc ls "${cmdline[2]}")" -- "${cmdline[3]}"
fi fi
if ((count == 4)) ; then if ((count == 4)) ; then
builtin compgen -W "$(command cat ~/.osc.projects)" -- "${cmdline[4]}" builtin compgen -W "$(command cat ~/.osc.projects)" -- "${cmdline[4]}"
fi fi
if ((count == 5)) ; then if ((count == 5)) ; then
builtin compgen -W "$(command osc ls "${cmdline[4]}")" -- "${cmdline[5]}" builtin compgen -W "$(command osc ls "${cmdline[4]}")" -- "${cmdline[5]}"
fi fi
esac esac
;; ;;
deleterequest|deletereq|dr) deleterequest|deletereq|dr)
if ((count == 1)) ; then if ((count == 1)) ; then
builtin compgen -W 'deleterequest deletereq dr' -- "${cmdline[1]}" builtin compgen -W 'deleterequest deletereq dr' -- "${cmdline[1]}"
fi fi
case "${cmdline[2]}" in case "${cmdline[2]}" in
*) *)
if ((count == 2)) ; then if ((count == 2)) ; then
builtin compgen -W "$(command cat ~/.osc.projects)" -- "${cmdline[2]}" builtin compgen -W "$(command cat ~/.osc.projects)" -- "${cmdline[2]}"
fi fi
if ((count == 3)) ; then if ((count == 3)) ; then
builtin compgen -W "$(osc ls "${cmdline[2]}")" -- "${cmdline[3]}" builtin compgen -W "$(osc ls "${cmdline[2]}")" -- "${cmdline[3]}"
fi fi
esac esac
;; ;;
changedevelrequest|changedevelreq|cr) changedevelrequest|changedevelreq|cr)
if ((count == 1)) ; then if ((count == 1)) ; then
builtin compgen -W 'changedevelrequest changedevelreq cr' -- "${cmdline[1]}" builtin compgen -W 'changedevelrequest changedevelreq cr' -- "${cmdline[1]}"
fi fi
case "${cmdline[2]}" in case "${cmdline[2]}" in
*) *)
if ((count == 2)) ; then if ((count == 2)) ; then
builtin compgen -W "$(command cat ~/.osc.projects)" -- "${cmdline[2]}" builtin compgen -W "$(command cat ~/.osc.projects)" -- "${cmdline[2]}"
fi fi
if ((count == 3)) ; then if ((count == 3)) ; then
builtin compgen -W "$(osc ls "${cmdline[2]}")" -- "${cmdline[3]}" builtin compgen -W "$(osc ls "${cmdline[2]}")" -- "${cmdline[3]}"
fi fi
if ((count == 4)) ; then if ((count == 4)) ; then
builtin compgen -W "$(command cat ~/.osc.projects)" -- "${cmdline[4]}" builtin compgen -W "$(command cat ~/.osc.projects)" -- "${cmdline[4]}"
fi fi
if ((count == 5)) ; then if ((count == 5)) ; then
builtin compgen -W "$(command osc ls "${cmdline[4]}")" -- "${cmdline[5]}" builtin compgen -W "$(command osc ls "${cmdline[4]}")" -- "${cmdline[5]}"
fi fi
esac esac
;; ;;
rdiff) rdiff)
if ((count == 1)) ; then if ((count == 1)) ; then
builtin compgen -W 'rdiff' -- "${cmdline[1]}" builtin compgen -W 'rdiff' -- "${cmdline[1]}"
fi fi
case "${cmdline[2]}" in case "${cmdline[2]}" in
*) *)
if ((count == 2)) ; then if ((count == 2)) ; then
builtin compgen -W "$(command cat ~/.osc.projects)" -- "${cmdline[2]}" builtin compgen -W "$(command cat ~/.osc.projects)" -- "${cmdline[2]}"
fi fi
if ((count == 3)) ; then if ((count == 3)) ; then
builtin compgen -W "$(osc ls "${cmdline[2]}")" -- "${cmdline[3]}" builtin compgen -W "$(osc ls "${cmdline[2]}")" -- "${cmdline[3]}"
fi fi
if ((count == 4)) ; then if ((count == 4)) ; then
builtin compgen -W "$(command cat ~/.osc.projects)" -P --oldprj= -- "${cmdline[4]#*=}" builtin compgen -W "$(command cat ~/.osc.projects)" -P --oldprj= -- "${cmdline[4]#*=}"
fi fi
if ((count == 5)) ; then if ((count == 5)) ; then
builtin compgen -W "$(command osc ls "${cmdline[4]#*=}")" -P --oldpkg= -- "${cmdline[5]#*=}" builtin compgen -W "$(command osc ls "${cmdline[4]#*=}")" -P --oldpkg= -- "${cmdline[5]#*=}"
fi fi
esac esac
;; ;;
ci|commit|checkin) ci|commit|checkin)
if ((count == 1)) ; then if ((count == 1)) ; then
builtin compgen -W 'ci commit checkin' -- "${cmdline[1]}" builtin compgen -W 'ci commit checkin' -- "${cmdline[1]}"
else else
for x in $(builtin compgen -f -X '.osc' -- "${cmdline[2]}"); do for x in $(builtin compgen -f -X '.osc' -- "${cmdline[2]}"); do
test -d $x && builtin echo $x/ || builtin echo $x test -d $x && builtin echo $x/ || builtin echo $x
done done
fi fi
;; ;;
co|checkout) co|checkout)
if ((count == 1)) ; then if ((count == 1)) ; then
builtin compgen -W 'co copypac checkout' -- "${cmdline[1]}" builtin compgen -W 'co copypac checkout' -- "${cmdline[1]}"
else else
if ((count == 2)) ; then if ((count == 2)) ; then
builtin compgen -W "$(command cat ~/.osc.projects)" -- "${cmdline[2]}" builtin compgen -W "$(command cat ~/.osc.projects)" -- "${cmdline[2]}"
fi fi
if ((count == 3)) ; then if ((count == 3)) ; then
builtin compgen -W "$(command osc ls "${cmdline[2]}")" -- "${cmdline[3]}" builtin compgen -W "$(command osc ls "${cmdline[2]}")" -- "${cmdline[3]}"
fi fi
fi fi
;; ;;
maintainer) maintainer)
if ((count == 1)) ; then if ((count == 1)) ; then
builtin compgen -W 'maintainer' -- "${cmdline[1]}" builtin compgen -W 'maintainer' -- "${cmdline[1]}"
else else
if ((count == 2)) ; then if ((count == 2)) ; then
builtin compgen -W "$(command cat ~/.osc.projects)" -- "${cmdline[2]}" builtin compgen -W "$(command cat ~/.osc.projects)" -- "${cmdline[2]}"
fi fi
if ((count == 3)) ; then if ((count == 3)) ; then
builtin compgen -W "$(command osc ls "${cmdline[2]}")" -- "${cmdline[3]}" builtin compgen -W "$(command osc ls "${cmdline[2]}")" -- "${cmdline[3]}"
fi fi
fi fi
;; ;;
up|update) up|update)
if ((count == 1)) ; then if ((count == 1)) ; then
builtin compgen -W 'up update' -- "${cmdline[1]}" builtin compgen -W 'up update' -- "${cmdline[1]}"
fi fi
if ((count == 2)) ; then if ((count == 2)) ; then
builtin compgen -W '--expand-link --unexpand-link' -- "${cmdline[2]}" builtin compgen -W '--expand-link --unexpand-link' -- "${cmdline[2]}"
fi fi
;; ;;
meta) meta)
if ((count == 1)) ; then if ((count == 1)) ; then
builtin compgen -W 'meta metafromspec' -- "${cmdline[1]}" builtin compgen -W 'meta metafromspec' -- "${cmdline[1]}"
fi fi
if ((count == 2)) ; then if ((count == 2)) ; then
builtin compgen -W 'prj pkg' -- "${cmdline[2]}" builtin compgen -W 'prj pkg' -- "${cmdline[2]}"
fi fi
if ((count == 3)) ; then if ((count == 3)) ; then
builtin compgen -W "$(command cat ~/.osc.projects)" -- "${cmdline[3]}" builtin compgen -W "$(command cat ~/.osc.projects)" -- "${cmdline[3]}"
fi fi
if ((count == 4)) && test "${cmdline[2]}" = pkg ; then if ((count == 4)) && test "${cmdline[2]}" = pkg ; then
builtin compgen -W "$(command osc ls "${cmdline[3]}")" -- "${cmdline[4]}" builtin compgen -W "$(command osc ls "${cmdline[3]}")" -- "${cmdline[4]}"
fi fi
if ((count == 5)) ; then if ((count == 5)) ; then
builtin compgen -W '--edit -e' -- "${cmdline[5]}" builtin compgen -W '--edit -e' -- "${cmdline[5]}"
fi fi
;; ;;
wipebinaries) wipebinaries)
if ((count == 1)) ; then if ((count == 1)) ; then
builtin compgen -W 'wipebinaries' -- "${cmdline[1]}" builtin compgen -W 'wipebinaries' -- "${cmdline[1]}"
fi fi
if ((count == 2)) ; then if ((count == 2)) ; then
builtin compgen -W "$(command cat ~/.osc.projects)" -- "${cmdline[2]}" builtin compgen -W "$(command cat ~/.osc.projects)" -- "${cmdline[2]}"
fi fi
if ((count == 3)) ; then if ((count == 3)) ; then
builtin compgen -W "$(command osc ls "${cmdline[2]}")" -- "${cmdline[3]}" builtin compgen -W "$(command osc ls "${cmdline[2]}")" -- "${cmdline[3]}"
fi fi
if ((count == 4)) ; then if ((count == 4)) ; then
builtin compgen -W "--expansion --broken --build-failed --build-disabled" -- "${cmdline[4]}" builtin compgen -W "--expansion --broken --build-failed --build-disabled" -- "${cmdline[4]}"
fi fi
;; ;;
help) help)
if ((count == 1)) ; then if ((count == 1)) ; then
builtin compgen -W 'help' -- "${cmdline[1]}" builtin compgen -W 'help' -- "${cmdline[1]}"
fi fi
((count == 2)) && builtin compgen -W "$(builtin echo ${osccmds[@]})" -- "${cmdline[2]}" ((count == 2)) && builtin compgen -W "$(builtin echo ${osccmds[@]})" -- "${cmdline[2]}"
;; ;;
search) search)
if ((count == 1)) ; then if ((count == 1)) ; then
builtin compgen -W 'search' -- "${cmdline[1]}" builtin compgen -W 'search' -- "${cmdline[1]}"
else else
oscsearch="--help --csv -i --involved -v --verbose --description --title \ oscsearch="--help --csv -i --involved -v --verbose --description --title \
--project --package -e --exact --repos-baseurl" --project --package -e --exact --repos-baseurl"
builtin compgen -W "${oscsearch}" -- "${cmdline[$count]}" builtin compgen -W "${oscsearch}" -- "${cmdline[$count]}"
fi fi
;; ;;
pr|prjresults) pr|prjresults)
if ((count == 1)) ; then if ((count == 1)) ; then
builtin compgen -W 'pr prjresults' -- "${cmdline[1]}" builtin compgen -W 'pr prjresults' -- "${cmdline[1]}"
fi fi
if ((count == 2)) ; then if ((count == 2)) ; then
builtin compgen -W "$(command cat ~/.osc.projects)" -- "${cmdline[2]}" builtin compgen -W "$(command cat ~/.osc.projects)" -- "${cmdline[2]}"
fi fi
if ((count > 2)) ; then if ((count > 2)) ; then
case "${cmdline[$((count-1))]}" in case "${cmdline[$((count-1))]}" in
-n|--name-filter*) -n|--name-filter*)
builtin compgen -W "$(command osc ls "${cmdline[2]}")" -- "${cmdline[$count]}" builtin compgen -W "$(command osc ls "${cmdline[2]}")" -- "${cmdline[$count]}"
;; ;;
-s|--status-filter*) -s|--status-filter*)
OIFS="$IFS"; IFS=: OIFS="$IFS"; IFS=:
builtin compgen -W 'disabled:failed:finished:building:succeeded:broken:scheduled:expansion error:blocked' -- "${cmdline[$count]}" builtin compgen -W 'disabled:failed:finished:building:succeeded:broken:scheduled:expansion error:blocked' -- "${cmdline[$count]}"
IFS="$OIFS" IFS="$OIFS"
;; ;;
-p|--project*) -p|--project*)
builtin compgen -W "$(command cat ~/.osc.projects)" -- "${cmdline[$count]}" builtin compgen -W "$(command cat ~/.osc.projects)" -- "${cmdline[$count]}"
;; ;;
*) *)
builtin compgen -W "-n --name-filter -s --status-filter -c --csv -q --hide-legend" -- "${cmdline[$count]}" builtin compgen -W "-n --name-filter -s --status-filter -c --csv -q --hide-legend" -- "${cmdline[$count]}"
;; ;;
esac esac
fi fi
;; ;;
r|results) r|results)
if ((count == 1)) ; then if ((count == 1)) ; then
builtin compgen -W 'r results' -- "${cmdline[1]}" builtin compgen -W 'r results' -- "${cmdline[1]}"
fi fi
if ((count == 2)) ; then if ((count == 2)) ; then
builtin compgen -W "$(command cat ~/.osc.projects)" -- "${cmdline[2]}" builtin compgen -W "$(command cat ~/.osc.projects)" -- "${cmdline[2]}"
fi fi
if ((count == 3)) ; then if ((count == 3)) ; then
builtin compgen -W "$(command osc ls "${cmdline[2]}")" -- "${cmdline[3]}" builtin compgen -W "$(command osc ls "${cmdline[2]}")" -- "${cmdline[3]}"
fi fi
if ((count > 3)) ; then if ((count > 3)) ; then
builtin compgen -W "-r --repo -a --arch -l --last-build --xml" -- "${cmdline[$count]}" builtin compgen -W "-r --repo -a --arch -l --last-build --xml" -- "${cmdline[$count]}"
fi fi
;; ;;
*) *)

View File

@ -9,21 +9,21 @@ from osc import core
release = False release = False
v = core.__version__ v = core.__version__
if (len(sys.argv) > 1 and sys.argv[1] == '-r'): if (len(sys.argv) > 1 and sys.argv[1] == '-r'):
release = True release = True
if release: if release:
if (v.endswith('_SVN')): if (v.endswith('_SVN')):
v=v[:-4] v=v[:-4]
print "don't forget to increase version in osc/core.py after release" print "don't forget to increase version in osc/core.py after release"
else: else:
v += subprocess.Popen(["svnversion", "."], stdout=subprocess.PIPE).stdout.read().strip() v += subprocess.Popen(["svnversion", "."], stdout=subprocess.PIPE).stdout.read().strip()
d = "osc-" + v d = "osc-" + v
f = d+".tar.bz2" f = d+".tar.bz2"
subprocess.check_call(["svn", "export", ".", d]) subprocess.check_call(["svn", "export", ".", d])
if release: if release:
# TODO: create tag for release # TODO: create tag for release
subprocess.check_call(["sed", "-ie", "/^__version__/s/_SVN//", d+"/osc/core.py"]) subprocess.check_call(["sed", "-ie", "/^__version__/s/_SVN//", d+"/osc/core.py"])
subprocess.check_call(["tar", "--force-local", "--owner=root", "--group=root", "-cjf", f, d]) subprocess.check_call(["tar", "--force-local", "--owner=root", "--group=root", "-cjf", f, d])
subprocess.call(["rm", "-rf", d]) # XXX how to do this in python properly? subprocess.call(["rm", "-rf", d]) # XXX how to do this in python properly?
print f print f

View File

@ -1,12 +1,11 @@
#!/usr/bin/env python #!/usr/bin/env python
# this wrapper exists so it can be put into /usr/bin, but still allows the # this wrapper exists so it can be put into /usr/bin, but still allows the
# python module to be called within the source directory during development # python module to be called within the source directory during development
import sys, locale import sys, locale
# this is a hack to make osc work as expected with utf-8 characters, no matter # this is a hack to make osc work as expected with utf-8 characters,
# how site.py is set... # no matter how site.py is set...
reload(sys) reload(sys)
loc = locale.getdefaultlocale()[1] loc = locale.getdefaultlocale()[1]
if not loc: if not loc:
@ -21,6 +20,3 @@ osccli = commandline.Osc()
r = babysitter.run(osccli) r = babysitter.run(osccli)
sys.exit(r) sys.exit(r)

View File

@ -1,14 +1,14 @@
# Copyright 2008,2009 Marcus Huewe <suse-tux@gmx.de> # Copyright 2008,2009 Marcus Huewe <suse-tux@gmx.de>
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 2 # modify it under the terms of the GNU General Public License version 2
# as published by the Free Software Foundation; # as published by the Free Software Foundation;
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
@ -97,7 +97,7 @@ class SectionLine(Line):
Line.__init__(self, sectname, 'section') Line.__init__(self, sectname, 'section')
self._lines = [] self._lines = []
self._dict = dict self._dict = dict
def _find(self, name): def _find(self, name):
for line in self._lines: for line in self._lines:
if line.name == name: if line.name == name:

View File

@ -141,7 +141,7 @@ def run(prg):
except AttributeError, e: except AttributeError, e:
print >>sys.stderr, e print >>sys.stderr, e
return 1 return 1
except RPMError, e: except RPMError, e:
print >>sys.stderr, e print >>sys.stderr, e
return 1 return 1

View File

@ -30,7 +30,7 @@ change_personality = {
's390': 's390', 's390': 's390',
} }
can_also_build = { can_also_build = {
'armv4l': [ 'armv4l' ], 'armv4l': [ 'armv4l' ],
'armv5el':[ 'armv4l', 'armv5el' ], 'armv5el':[ 'armv4l', 'armv5el' ],
'armv6l' :[ 'armv4l', 'armv5el' ], 'armv6l' :[ 'armv4l', 'armv5el' ],
@ -83,7 +83,7 @@ class Buildinfo:
self.buildarch = root.find('arch').text self.buildarch = root.find('arch').text
self.release = "0" self.release = "0"
if root.find('release') != None: if root.find('release') != None:
self.release = root.find('release').text self.release = root.find('release').text
self.downloadurl = root.get('downloadurl') self.downloadurl = root.get('downloadurl')
self.debuginfo = 0 self.debuginfo = 0
if root.find('debuginfo') != None: if root.find('debuginfo') != None:
@ -125,9 +125,9 @@ class Pac:
def __init__(self, node, buildarch, pacsuffix, apiurl, localpkgs = []): def __init__(self, node, buildarch, pacsuffix, apiurl, localpkgs = []):
self.mp = {} self.mp = {}
for i in ['name', 'package', for i in ['name', 'package',
'version', 'release', 'version', 'release',
'project', 'repository', 'project', 'repository',
'preinstall', 'vminstall', 'noinstall', 'runscripts', 'preinstall', 'vminstall', 'noinstall', 'runscripts',
]: ]:
self.mp[i] = node.get(i) self.mp[i] = node.get(i)
@ -151,7 +151,7 @@ class Pac:
if pacsuffix == 'deb' and not (self.mp['name'] and self.mp['arch'] and self.mp['version']): if pacsuffix == 'deb' and not (self.mp['name'] and self.mp['arch'] and self.mp['version']):
raise oscerr.APIError( raise oscerr.APIError(
"buildinfo for package %s/%s/%s is incomplete" "buildinfo for package %s/%s/%s is incomplete"
% (self.mp['name'], self.mp['arch'], self.mp['version'])) % (self.mp['name'], self.mp['arch'], self.mp['version']))
self.mp['apiurl'] = apiurl self.mp['apiurl'] = apiurl
@ -186,7 +186,7 @@ class Pac:
self.fullpartname = os.path.join(self.localdir, self.partname) self.fullpartname = os.path.join(self.localdir, self.partname)
self.url_local = 'file://%s/' % self.fullfilename self.url_local = 'file://%s/' % self.fullfilename
# first, add the local URL # first, add the local URL
self.urllist.append(self.url_local) self.urllist.append(self.url_local)
# remote URLs # remote URLs
@ -203,21 +203,21 @@ class Pac:
def get_built_files(pacdir, pactype): def get_built_files(pacdir, pactype):
if pactype == 'rpm': if pactype == 'rpm':
b_built = subprocess.Popen(['find', os.path.join(pacdir, 'RPMS'), b_built = subprocess.Popen(['find', os.path.join(pacdir, 'RPMS'),
'-name', '*.rpm'], '-name', '*.rpm'],
stdout=subprocess.PIPE).stdout.read().strip() stdout=subprocess.PIPE).stdout.read().strip()
s_built = subprocess.Popen(['find', os.path.join(pacdir, 'SRPMS'), s_built = subprocess.Popen(['find', os.path.join(pacdir, 'SRPMS'),
'-name', '*.rpm'], '-name', '*.rpm'],
stdout=subprocess.PIPE).stdout.read().strip() stdout=subprocess.PIPE).stdout.read().strip()
elif pactype == 'kiwi': elif pactype == 'kiwi':
b_built = subprocess.Popen(['find', os.path.join(pacdir, 'KIWI'), b_built = subprocess.Popen(['find', os.path.join(pacdir, 'KIWI'),
'-type', 'f'], '-type', 'f'],
stdout=subprocess.PIPE).stdout.read().strip() stdout=subprocess.PIPE).stdout.read().strip()
else: else:
b_built = subprocess.Popen(['find', os.path.join(pacdir, 'DEBS'), b_built = subprocess.Popen(['find', os.path.join(pacdir, 'DEBS'),
'-name', '*.deb'], '-name', '*.deb'],
stdout=subprocess.PIPE).stdout.read().strip() stdout=subprocess.PIPE).stdout.read().strip()
s_built = subprocess.Popen(['find', os.path.join(pacdir, 'SOURCES.DEB'), s_built = subprocess.Popen(['find', os.path.join(pacdir, 'SOURCES.DEB'),
'-type', 'f'], '-type', 'f'],
stdout=subprocess.PIPE).stdout.read().strip() stdout=subprocess.PIPE).stdout.read().strip()
return s_built, b_built return s_built, b_built
@ -338,7 +338,7 @@ def main(opts, argv):
return 1 return 1
# make it possible to override configuration of the rc file # make it possible to override configuration of the rc file
for var in ['OSC_PACKAGECACHEDIR', 'OSC_SU_WRAPPER', 'OSC_BUILD_ROOT']: for var in ['OSC_PACKAGECACHEDIR', 'OSC_SU_WRAPPER', 'OSC_BUILD_ROOT']:
val = os.getenv(var) val = os.getenv(var)
if val: if val:
if var.startswith('OSC_'): var = var[4:] if var.startswith('OSC_'): var = var[4:]
@ -373,23 +373,23 @@ def main(opts, argv):
bi_file = None bi_file = None
try: try:
if opts.noinit: if opts.noinit:
if not os.path.isfile(bi_file_name): if not os.path.isfile(bi_file_name):
print >>sys.stderr, '--noinit is not possible, no local build info file' print >>sys.stderr, '--noinit is not possible, no local build info file'
sys.exit(1) sys.exit(1)
print 'Use local .buildinfo.xml file as build description' print 'Use local .buildinfo.xml file as build description'
bi_file = open(bi_file_name, 'r') bi_file = open(bi_file_name, 'r')
else: else:
print 'Getting buildinfo from server and store to local directory as .buildinfo.xml' print 'Getting buildinfo from server and store to local directory as .buildinfo.xml'
bi_file = open(bi_file_name, 'w+') bi_file = open(bi_file_name, 'w+')
bi_text = ''.join(get_buildinfo(apiurl, bi_text = ''.join(get_buildinfo(apiurl,
prj, prj,
pac, pac,
repo, repo,
arch, arch,
specfile=build_descr_data, specfile=build_descr_data,
addlist=extra_pkgs)) addlist=extra_pkgs))
bi_file.write(bi_text) bi_file.write(bi_text)
bi_file.flush() bi_file.flush()
except urllib2.HTTPError, e: except urllib2.HTTPError, e:
if e.code == 404: if e.code == 404:
# check what caused the 404 # check what caused the 404
@ -415,7 +415,7 @@ def main(opts, argv):
buildargs.append('--debug') buildargs.append('--debug')
buildargs = ' '.join(set(buildargs)) buildargs = ' '.join(set(buildargs))
# real arch of this machine # real arch of this machine
# vs. # vs.
# arch we are supposed to build for # arch we are supposed to build for
if hostarch != bi.buildarch: if hostarch != bi.buildarch:
@ -445,7 +445,7 @@ def main(opts, argv):
# transform 'url1, url2, url3' form into a list # transform 'url1, url2, url3' form into a list
if 'urllist' in config: if 'urllist' in config:
if type(config['urllist']) == str: if type(config['urllist']) == str:
re_clist = re.compile('[, ]+') re_clist = re.compile('[, ]+')
urllist = [ i.strip() for i in re_clist.split(config['urllist'].strip()) ] urllist = [ i.strip() for i in re_clist.split(config['urllist'].strip()) ]
else: else:
urllist = config['urllist'] urllist = config['urllist']
@ -455,7 +455,7 @@ def main(opts, argv):
urllist.append(bi.downloadurl + '/%(extproject)s/%(extrepository)s/%(arch)s/%(filename)s') urllist.append(bi.downloadurl + '/%(extproject)s/%(extrepository)s/%(arch)s/%(filename)s')
urllist.append( '%(apiurl)s/build/%(project)s/%(repository)s/%(repoarch)s/%(repopackage)s/%(repofilename)s' ) urllist.append( '%(apiurl)s/build/%(project)s/%(repository)s/%(repoarch)s/%(repopackage)s/%(repofilename)s' )
fetcher = Fetcher(cachedir = config['packagecachedir'], fetcher = Fetcher(cachedir = config['packagecachedir'],
urllist = urllist, urllist = urllist,
api_host_options = config['api_host_options'], api_host_options = config['api_host_options'],
offline = opts.noinit, offline = opts.noinit,
@ -535,18 +535,18 @@ def main(opts, argv):
vm_options="" vm_options=""
if config['build-device'] and config['build-memory'] and config['build-type']: if config['build-device'] and config['build-memory'] and config['build-type']:
if config['build-type'] == "kvm": if config['build-type'] == "kvm":
vm_options="--kvm " + config['build-device'] vm_options="--kvm " + config['build-device']
elif config['build-type'] == "xen": elif config['build-type'] == "xen":
vm_options="--xen " + config['build-device'] vm_options="--xen " + config['build-device']
else: else:
print "ERROR: unknown VM is set ! (" + config['build-type'] + ")" print "ERROR: unknown VM is set ! (" + config['build-type'] + ")"
sys.exit(1) sys.exit(1)
if config['build-swap']: if config['build-swap']:
vm_options+=" --swap " + config['build-swap'] vm_options+=" --swap " + config['build-swap']
if config['build-memory']: if config['build-memory']:
vm_options+=" --memory " + config['build-memory'] vm_options+=" --memory " + config['build-memory']
print 'Running build' print 'Running build'
# special handling for overlay and rsync-src/dest # special handling for overlay and rsync-src/dest
specialcmdopts = " " specialcmdopts = " "
@ -583,13 +583,13 @@ def main(opts, argv):
cmd = '%s --root=%s --rpmlist=%s --dist=%s %s --arch=%s --release=%s %s %s %s' \ cmd = '%s --root=%s --rpmlist=%s --dist=%s %s --arch=%s --release=%s %s %s %s' \
% (config['build-cmd'], % (config['build-cmd'],
config['build-root'], config['build-root'],
rpmlist_file.name, rpmlist_file.name,
bc_file.name, bc_file.name,
specialcmdopts, specialcmdopts,
bi.buildarch, bi.buildarch,
bi.release, bi.release,
vm_options, vm_options,
build_descr, build_descr,
buildargs) buildargs)
if config['su-wrapper'].startswith('su '): if config['su-wrapper'].startswith('su '):
@ -603,7 +603,7 @@ def main(opts, argv):
cmd = (change_personality.get(bi.buildarch, '') + ' ' + cmd).strip() cmd = (change_personality.get(bi.buildarch, '') + ' ' + cmd).strip()
rc = subprocess.call(cmd, shell=True) rc = subprocess.call(cmd, shell=True)
if rc: if rc:
print print
print 'The buildroot was:', config['build-root'] print 'The buildroot was:', config['build-root']
sys.exit(rc) sys.exit(rc)
@ -615,7 +615,7 @@ def main(opts, argv):
if os.path.exists(pacdir): if os.path.exists(pacdir):
(s_built, b_built) = get_built_files(pacdir, bi.pacsuffix) (s_built, b_built) = get_built_files(pacdir, bi.pacsuffix)
print print
if s_built: print s_built if s_built: print s_built
print print

View File

@ -103,7 +103,7 @@ class CmdlnUserError(Exception):
def alias(*aliases): def alias(*aliases):
"""Decorator to add aliases for Cmdln.do_* command handlers. """Decorator to add aliases for Cmdln.do_* command handlers.
Example: Example:
class MyShell(cmdln.Cmdln): class MyShell(cmdln.Cmdln):
@cmdln.alias("!", "sh") @cmdln.alias("!", "sh")
@ -177,7 +177,7 @@ class RawCmdln(cmd.Cmd):
man_options_header = MAN_OPTIONS_HEADER man_options_header = MAN_OPTIONS_HEADER
man_footer = MAN_FOOTER man_footer = MAN_FOOTER
def __init__(self, completekey='tab', def __init__(self, completekey='tab',
stdin=None, stdout=None, stderr=None): stdin=None, stdout=None, stderr=None):
"""Cmdln(completekey='tab', stdin=None, stdout=None, stderr=None) """Cmdln(completekey='tab', stdin=None, stdout=None, stderr=None)
@ -185,11 +185,11 @@ class RawCmdln(cmd.Cmd):
completion key; it defaults to the Tab key. If completekey is completion key; it defaults to the Tab key. If completekey is
not None and the readline module is available, command completion not None and the readline module is available, command completion
is done automatically. is done automatically.
The optional arguments 'stdin', 'stdout' and 'stderr' specify The optional arguments 'stdin', 'stdout' and 'stderr' specify
alternate input, output and error output file objects; if not alternate input, output and error output file objects; if not
specified, sys.* are used. specified, sys.* are used.
If 'stdout' but not 'stderr' is specified, stdout is used for If 'stdout' but not 'stderr' is specified, stdout is used for
error output. This is to provide least surprise for users used error output. This is to provide least surprise for users used
to only the 'stdin' and 'stdout' options with cmd.Cmd. to only the 'stdin' and 'stdout' options with cmd.Cmd.
@ -230,7 +230,7 @@ class RawCmdln(cmd.Cmd):
can return None to have no options at the top-level. Typically can return None to have no options at the top-level. Typically
an instance of CmdlnOptionParser should be returned. an instance of CmdlnOptionParser should be returned.
""" """
version = (self.version is not None version = (self.version is not None
and "%s %s" % (self._name_str, self.version) and "%s %s" % (self._name_str, self.version)
or None) or None)
return CmdlnOptionParser(self, version=version) return CmdlnOptionParser(self, version=version)
@ -256,14 +256,14 @@ class RawCmdln(cmd.Cmd):
class MyCmd(cmdln.Cmdln): class MyCmd(cmdln.Cmdln):
name = "mycmd" name = "mycmd"
... ...
if __name__ == "__main__": if __name__ == "__main__":
MyCmd().main() MyCmd().main()
By default this will use sys.argv to issue a single command to By default this will use sys.argv to issue a single command to
'MyCmd', then exit. The 'loop' argument can be use to control 'MyCmd', then exit. The 'loop' argument can be use to control
interactive shell behaviour. interactive shell behaviour.
Arguments: Arguments:
"argv" (optional, default sys.argv) is the command to run. "argv" (optional, default sys.argv) is the command to run.
It must be a sequence, where the first element is the It must be a sequence, where the first element is the
@ -316,7 +316,7 @@ class RawCmdln(cmd.Cmd):
def cmd(self, argv): def cmd(self, argv):
"""Run one command and exit. """Run one command and exit.
"argv" is the arglist for the command to run. argv[0] is the "argv" is the arglist for the command to run. argv[0] is the
command to run. If argv is an empty list then the command to run. If argv is an empty list then the
'emptyline' handler is run. 'emptyline' handler is run.
@ -352,7 +352,7 @@ class RawCmdln(cmd.Cmd):
"""Repeatedly issue a prompt, accept input, parse into an argv, and """Repeatedly issue a prompt, accept input, parse into an argv, and
dispatch (via .precmd(), .onecmd() and .postcmd()), passing them dispatch (via .precmd(), .onecmd() and .postcmd()), passing them
the argv. In other words, start a shell. the argv. In other words, start a shell.
"intro" (optional) is a introductory message to print when "intro" (optional) is a introductory message to print when
starting the command loop. This overrides the class starting the command loop. This overrides the class
"intro" attribute, if any. "intro" attribute, if any.
@ -404,7 +404,7 @@ class RawCmdln(cmd.Cmd):
interpreted, but after the input prompt is generated and issued. interpreted, but after the input prompt is generated and issued.
"argv" is the cmd to run. "argv" is the cmd to run.
Returns an argv to run (i.e. this method can modify the command Returns an argv to run (i.e. this method can modify the command
to run). to run).
""" """
@ -412,7 +412,7 @@ class RawCmdln(cmd.Cmd):
def postcmd(self, argv): def postcmd(self, argv):
"""Hook method executed just after a command dispatch is finished. """Hook method executed just after a command dispatch is finished.
"argv" is the command that was run. "argv" is the command that was run.
""" """
pass pass
@ -454,7 +454,7 @@ class RawCmdln(cmd.Cmd):
"""Hook called to handle a command for which there is no handler. """Hook called to handle a command for which there is no handler.
"argv" is the command and arguments to run. "argv" is the command and arguments to run.
The default implementation writes and error message to stderr The default implementation writes and error message to stderr
and returns an error exit status. and returns an error exit status.
@ -490,7 +490,7 @@ class RawCmdln(cmd.Cmd):
"cmd" is the command name on which help was requested. "cmd" is the command name on which help was requested.
"known" is a boolean indicating if this command is known "known" is a boolean indicating if this command is known
(i.e. if there is a handler for it). (i.e. if there is a handler for it).
Returns a return code. Returns a return code.
""" """
if known: if known:
@ -564,7 +564,7 @@ class RawCmdln(cmd.Cmd):
${name} man ${name} man
""" """
self.stdout.write(self.man_header % { self.stdout.write(self.man_header % {
'date': date.today().strftime('%b %Y'), 'date': date.today().strftime('%b %Y'),
'version': self.get_version(), 'version': self.get_version(),
'name': self.name, 'name': self.name,
'ucname': self.name.upper() 'ucname': self.name.upper()
@ -652,7 +652,7 @@ class RawCmdln(cmd.Cmd):
i.e. using @cmdln.option decorators or manually setting the i.e. using @cmdln.option decorators or manually setting the
'optparser' attribute on the 'do_*' method.) 'optparser' attribute on the 'do_*' method.)
Returns the processed help. Returns the processed help.
""" """
preprocessors = { preprocessors = {
"${name}": self._help_preprocess_name, "${name}": self._help_preprocess_name,
@ -687,7 +687,7 @@ class RawCmdln(cmd.Cmd):
block = self.optparser.format_option_help() + '\n' block = self.optparser.format_option_help() + '\n'
else: else:
block = "" block = ""
help = help.replace(indent+marker+suffix, block, 1) help = help.replace(indent+marker+suffix, block, 1)
return help return help
@ -724,7 +724,7 @@ class RawCmdln(cmd.Cmd):
doc = handler.__doc__ doc = handler.__doc__
else: else:
doc = helpfunc() doc = helpfunc()
# Strip "${cmd_name}: " from the start of a command's doc. Best # Strip "${cmd_name}: " from the start of a command's doc. Best
# practice dictates that command help strings begin with this, but # practice dictates that command help strings begin with this, but
# it isn't at all wanted for the command list. # it isn't at all wanted for the command list.
@ -786,7 +786,7 @@ class RawCmdln(cmd.Cmd):
handler = self._get_cmd_handler(cmdname) handler = self._get_cmd_handler(cmdname)
if not handler: if not handler:
raise CmdlnError("cannot preprocess '%s' into help string: " raise CmdlnError("cannot preprocess '%s' into help string: "
"could not find command handler for %r" "could not find command handler for %r"
% (marker, cmdname)) % (marker, cmdname))
s = cmdname s = cmdname
if hasattr(handler, "aliases"): if hasattr(handler, "aliases"):
@ -802,7 +802,7 @@ class RawCmdln(cmd.Cmd):
handler = self._get_cmd_handler(cmdname) handler = self._get_cmd_handler(cmdname)
if not handler: if not handler:
raise CmdlnError("cannot preprocess '%s' into help string: " raise CmdlnError("cannot preprocess '%s' into help string: "
"could not find command handler for %r" "could not find command handler for %r"
% (marker, cmdname)) % (marker, cmdname))
indent, indent_width = _get_indent(marker, help) indent, indent_width = _get_indent(marker, help)
suffix = _get_trailing_whitespace(marker, help) suffix = _get_trailing_whitespace(marker, help)
@ -838,7 +838,7 @@ class RawCmdln(cmd.Cmd):
# keyword arguments from the command line. Could # keyword arguments from the command line. Could
# *perhaps* consider: arg=value arg2=value2 ... # *perhaps* consider: arg=value arg2=value2 ...
warnings.warn("argument '**%s' on '%s.%s' command " warnings.warn("argument '**%s' on '%s.%s' command "
"handler will never get values" "handler will never get values"
% (name, self.__class__.__name__, % (name, self.__class__.__name__,
func.func_name)) func.func_name))
if co_flags & CO_FLAGS_ARGS: if co_flags & CO_FLAGS_ARGS:
@ -870,7 +870,7 @@ class RawCmdln(cmd.Cmd):
handler = self._get_cmd_handler(cmdname) handler = self._get_cmd_handler(cmdname)
if not handler: if not handler:
raise CmdlnError("cannot preprocess '%s' into help string: " raise CmdlnError("cannot preprocess '%s' into help string: "
"could not find command handler for %r" "could not find command handler for %r"
% (marker, cmdname)) % (marker, cmdname))
indent, indent_width = _get_indent(marker, help) indent, indent_width = _get_indent(marker, help)
suffix = _get_trailing_whitespace(marker, help) suffix = _get_trailing_whitespace(marker, help)
@ -963,7 +963,7 @@ class StopOptionProcessing(Exception):
StopIteration. This is raised by _OptionParserEx's default "help" StopIteration. This is raised by _OptionParserEx's default "help"
and "version" option actions and can be raised by custom option and "version" option actions and can be raised by custom option
callbacks too. callbacks too.
Hence the typical CmdlnOptionParser (a subclass of _OptionParserEx) Hence the typical CmdlnOptionParser (a subclass of _OptionParserEx)
usage is: usage is:
@ -1059,7 +1059,7 @@ class SubCmdOptionParser(_OptionParserEx):
def option(*args, **kwargs): def option(*args, **kwargs):
"""Decorator to add an option to the optparser argument of a Cmdln """Decorator to add an option to the optparser argument of a Cmdln
subcommand. subcommand.
Example: Example:
class MyShell(cmdln.Cmdln): class MyShell(cmdln.Cmdln):
@cmdln.option("-f", "--force", help="force removal") @cmdln.option("-f", "--force", help="force removal")
@ -1206,14 +1206,14 @@ class Cmdln(RawCmdln):
raise CmdlnError("incorrect argcount for %s(): takes %d, must " raise CmdlnError("incorrect argcount for %s(): takes %d, must "
"take 2 for 'argv' signature or 3+ for 'opts' " "take 2 for 'argv' signature or 3+ for 'opts' "
"signature" % (handler.__name__, co_argcount)) "signature" % (handler.__name__, co_argcount))
#---- internal support functions #---- internal support functions
def _format_linedata(linedata, indent, indent_width): def _format_linedata(linedata, indent, indent_width):
"""Format specific linedata into a pleasant layout. """Format specific linedata into a pleasant layout.
"linedata" is a list of 2-tuples of the form: "linedata" is a list of 2-tuples of the form:
(<item-display-string>, <item-docstring>) (<item-display-string>, <item-docstring>)
"indent" is a string to use for one level of indentation "indent" is a string to use for one level of indentation
@ -1242,7 +1242,7 @@ def _format_linedata(linedata, indent, indent_width):
def _summarize_doc(doc, length=60): def _summarize_doc(doc, length=60):
r"""Parse out a short one line summary from the given doclines. r"""Parse out a short one line summary from the given doclines.
"doc" is the doc string to summarize. "doc" is the doc string to summarize.
"length" is the max length for the summary "length" is the max length for the summary
@ -1274,19 +1274,19 @@ def _summarize_doc(doc, length=60):
summary = ' '.join(summlines) summary = ' '.join(summlines)
if len(summary) > length: if len(summary) > length:
summary = summary[:length-3] + "..." summary = summary[:length-3] + "..."
return summary return summary
def line2argv(line): def line2argv(line):
r"""Parse the given line into an argument vector. r"""Parse the given line into an argument vector.
"line" is the line of input to parse. "line" is the line of input to parse.
This may get niggly when dealing with quoting and escaping. The This may get niggly when dealing with quoting and escaping. The
current state of this parsing may not be completely thorough/correct current state of this parsing may not be completely thorough/correct
in this respect. in this respect.
>>> from cmdln import line2argv >>> from cmdln import line2argv
>>> line2argv("foo") >>> line2argv("foo")
['foo'] ['foo']
@ -1298,7 +1298,7 @@ def line2argv(line):
['foo', 'bar'] ['foo', 'bar']
Quote handling: Quote handling:
>>> line2argv("'foo bar'") >>> line2argv("'foo bar'")
['foo bar'] ['foo bar']
>>> line2argv('"foo bar"') >>> line2argv('"foo bar"')
@ -1379,9 +1379,9 @@ def line2argv(line):
def argv2line(argv): def argv2line(argv):
r"""Put together the given argument vector into a command line. r"""Put together the given argument vector into a command line.
"argv" is the argument vector to process. "argv" is the argument vector to process.
>>> from cmdln import argv2line >>> from cmdln import argv2line
>>> argv2line(['foo']) >>> argv2line(['foo'])
'foo' 'foo'
@ -1414,18 +1414,18 @@ def argv2line(argv):
# Recipe: dedent (0.1) in /Users/trentm/tm/recipes/cookbook # Recipe: dedent (0.1) in /Users/trentm/tm/recipes/cookbook
def _dedentlines(lines, tabsize=8, skip_first_line=False): def _dedentlines(lines, tabsize=8, skip_first_line=False):
"""_dedentlines(lines, tabsize=8, skip_first_line=False) -> dedented lines """_dedentlines(lines, tabsize=8, skip_first_line=False) -> dedented lines
"lines" is a list of lines to dedent. "lines" is a list of lines to dedent.
"tabsize" is the tab width to use for indent width calculations. "tabsize" is the tab width to use for indent width calculations.
"skip_first_line" is a boolean indicating if the first line should "skip_first_line" is a boolean indicating if the first line should
be skipped for calculating the indent width and for dedenting. be skipped for calculating the indent width and for dedenting.
This is sometimes useful for docstrings and similar. This is sometimes useful for docstrings and similar.
Same as dedent() except operates on a sequence of lines. Note: the Same as dedent() except operates on a sequence of lines. Note: the
lines list is modified **in-place**. lines list is modified **in-place**.
""" """
DEBUG = False DEBUG = False
if DEBUG: if DEBUG:
print "dedent: dedent(..., tabsize=%d, skip_first_line=%r)"\ print "dedent: dedent(..., tabsize=%d, skip_first_line=%r)"\
% (tabsize, skip_first_line) % (tabsize, skip_first_line)
indents = [] indents = []
@ -1487,7 +1487,7 @@ def _dedent(text, tabsize=8, skip_first_line=False):
"skip_first_line" is a boolean indicating if the first line should "skip_first_line" is a boolean indicating if the first line should
be skipped for calculating the indent width and for dedenting. be skipped for calculating the indent width and for dedenting.
This is sometimes useful for docstrings and similar. This is sometimes useful for docstrings and similar.
textwrap.dedent(s), but don't expand tabs to spaces textwrap.dedent(s), but don't expand tabs to spaces
""" """
lines = text.splitlines(1) lines = text.splitlines(1)

View File

@ -542,11 +542,11 @@ class Osc(cmdln.Cmdln):
src_update = None src_update = None
# we should check here for home:<id>:branch and default to update, but that would require OBS 1.7 server # we should check here for home:<id>:branch and default to update, but that would require OBS 1.7 server
if opts.cleanup: if opts.cleanup:
src_update = "cleanup" src_update = "cleanup"
elif opts.no_cleanup: elif opts.no_cleanup:
src_update = "update" src_update = "update"
elif opts.no_update: elif opts.no_update:
src_update = "noupdate" src_update = "noupdate"
args = slash_split(args) args = slash_split(args)
@ -616,15 +616,15 @@ Warning: failed to fetch meta data for '%s' package '%s' (new package?) """ \
% (dst_project, dst_package) % (dst_project, dst_package)
pass pass
if devloc \ if devloc and \
and dst_project != devloc \ dst_project != devloc and \
and src_project != devloc: src_project != devloc:
print """\ print """\
Sorry, but a different project, %s, is defined as the place where development Sorry, but a different project, %s, is defined as the place where development
of the package %s primarily takes place. of the package %s primarily takes place.
Please submit there instead, or use --nodevelproject to force direct submission.""" \ Please submit there instead, or use --nodevelproject to force direct submission.""" \
% (devloc, dst_package) % (devloc, dst_package)
sys.exit(1) sys.exit(1)
if opts.diff: if opts.diff:
print 'old: %s/%s\nnew: %s/%s' %(dst_project, dst_package, src_project, src_package) print 'old: %s/%s\nnew: %s/%s' %(dst_project, dst_package, src_project, src_package)
rdiff = server_diff(apiurl, rdiff = server_diff(apiurl,
@ -681,7 +681,7 @@ Please submit there instead, or use --nodevelproject to force direct submission.
project = args[0] project = args[0]
package = None package = None
if len(args) > 1: if len(args) > 1:
package = args[1] package = args[1]
if not opts.message: if not opts.message:
opts.message = edit_message() opts.message = edit_message()
@ -717,7 +717,7 @@ Please submit there instead, or use --nodevelproject to force direct submission.
package = args[1] package = args[1]
devel_package = package devel_package = package
if len(args) > 3: if len(args) > 3:
devel_package = args[3] devel_package = args[3]
if not opts.message: if not opts.message:
opts.message = edit_message() opts.message = edit_message()
@ -892,7 +892,7 @@ Please submit there instead, or use --nodevelproject to force direct submission.
import time import time
days = opts.days or conf.config['request_list_days'] days = opts.days or conf.config['request_list_days']
since = '' since = ''
try: try:
days = int(days) days = int(days)
except ValueError: except ValueError:
days = 0 days = 0
@ -1036,9 +1036,9 @@ Please submit there instead, or use --nodevelproject to force direct submission.
for p in packages: for p in packages:
print "setting revision for package", p print "setting revision for package", p
if opts.unset: if opts.unset:
rev=-1 rev=-1
else: else:
rev, dummy = parseRevisionOption(opts.revision) rev, dummy = parseRevisionOption(opts.revision)
set_link_rev(apiurl, project, p, rev) set_link_rev(apiurl, project, p, rev)
@ -1092,7 +1092,7 @@ Please submit there instead, or use --nodevelproject to force direct submission.
return 1 return 1
if opts.current: if opts.current:
rev = show_upstream_rev(conf.config['apiurl'], src_project, src_package); rev = show_upstream_rev(conf.config['apiurl'], src_project, src_package)
if rev and not checkRevision(src_project, src_package, rev): if rev and not checkRevision(src_project, src_package, rev):
print >>sys.stderr, 'Revision \'%s\' does not exist' % rev print >>sys.stderr, 'Revision \'%s\' does not exist' % rev
@ -1207,7 +1207,7 @@ Please submit there instead, or use --nodevelproject to force direct submission.
if src_project == dst_project and \ if src_project == dst_project and \
src_package == dst_package and \ src_package == dst_package and \
src_apiurl == dst_apiurl: src_apiurl == dst_apiurl:
raise oscerr.WrongArgs('Source and destination are the same.') raise oscerr.WrongArgs('Source and destination are the same.')
if src_apiurl != dst_apiurl: if src_apiurl != dst_apiurl:
opts.client_side_copy = True opts.client_side_copy = True
@ -1218,7 +1218,7 @@ Please submit there instead, or use --nodevelproject to force direct submission.
comment = opts.message comment = opts.message
else: else:
if not rev: if not rev:
rev = show_upstream_rev(src_apiurl, src_project, src_package); rev = show_upstream_rev(src_apiurl, src_project, src_package)
comment = 'osc copypac from project:%s package:%s revision:%s' % ( src_project, src_package, rev ) comment = 'osc copypac from project:%s package:%s revision:%s' % ( src_project, src_package, rev )
r = copy_pac(src_apiurl, src_project, src_package, r = copy_pac(src_apiurl, src_project, src_package,
@ -1256,7 +1256,7 @@ Please submit there instead, or use --nodevelproject to force direct submission.
home:USERNAME:branches:PROJECT/PACKAGE home:USERNAME:branches:PROJECT/PACKAGE
if nothing else specified. if nothing else specified.
With getpac or bco, the branched package will come from With getpac or bco, the branched package will come from
%(getpac_default_project)s %(getpac_default_project)s
if nothing else specified. if nothing else specified.
@ -1286,8 +1286,8 @@ Please submit there instead, or use --nodevelproject to force direct submission.
tpackage = args[3] tpackage = args[3]
r = branch_pkg(conf.config['apiurl'], args[0], args[1], r = branch_pkg(conf.config['apiurl'], args[0], args[1],
nodevelproject=opts.nodevelproject, rev=opts.revision, nodevelproject=opts.nodevelproject, rev=opts.revision,
target_project=tproject, target_package=tpackage, target_project=tproject, target_package=tpackage,
return_existing=opts.checkout) return_existing=opts.checkout)
expected = 'home:%s:branches:%s' % (conf.config['user'], args[0]) expected = 'home:%s:branches:%s' % (conf.config['user'], args[0])
@ -1311,7 +1311,7 @@ Please submit there instead, or use --nodevelproject to force direct submission.
package = args[1] package = args[1]
if tpackage: if tpackage:
package = tpackage package = tpackage
if opts.checkout: if opts.checkout:
checkout_package(conf.config['apiurl'], r, package, checkout_package(conf.config['apiurl'], r, package,
expand_link=True, prj_dir=r) expand_link=True, prj_dir=r)
@ -1353,11 +1353,11 @@ Please submit there instead, or use --nodevelproject to force direct submission.
pkgs = args[1:] pkgs = args[1:]
if pkgs: if pkgs:
for pkg in pkgs: for pkg in pkgs:
# careful: if pkg is an empty string, the package delete request results # careful: if pkg is an empty string, the package delete request results
# into a project delete request - which works recursively... # into a project delete request - which works recursively...
if pkg: if pkg:
delete_package(conf.config['apiurl'], prj, pkg) delete_package(conf.config['apiurl'], prj, pkg)
elif len(meta_get_packagelist(conf.config['apiurl'], prj)) >= 1 and not opts.force: elif len(meta_get_packagelist(conf.config['apiurl'], prj)) >= 1 and not opts.force:
print >>sys.stderr, 'Project contains packages. It must be empty before deleting it. ' \ print >>sys.stderr, 'Project contains packages. It must be empty before deleting it. ' \
'If you are sure that you want to remove this project and all its ' \ 'If you are sure that you want to remove this project and all its ' \
@ -1521,8 +1521,8 @@ Please submit there instead, or use --nodevelproject to force direct submission.
def do_install(self, subcmd, opts, *args): def do_install(self, subcmd, opts, *args):
"""${cmd_name}: install a package after build via zypper in -r """${cmd_name}: install a package after build via zypper in -r
Not implemented yet. Use osc repourls, Not implemented yet. Use osc repourls,
select the url you best like (standard), select the url you best like (standard),
chop off after the last /, this should work with zypper. chop off after the last /, this should work with zypper.
@ -1532,9 +1532,9 @@ Please submit there instead, or use --nodevelproject to force direct submission.
args = slash_split(args) args = slash_split(args)
args = expand_proj_pack(args) args = expand_proj_pack(args)
cmd = "sudo zypper -p http://download.opensuse.org/repositories/%s/%s --no-refresh -v in %s" % (re.sub(':',':/',args[0]), 'openSUSE_11.1', args[1]) cmd = "sudo zypper -p http://download.opensuse.org/repositories/%s/%s --no-refresh -v in %s" % (re.sub(':',':/',args[0]), 'openSUSE_11.1', args[1])
print self.do_install.__doc__ print self.do_install.__doc__
print "Example: \n" + cmd print "Example: \n" + cmd
def do_repourls(self, subcmd, opts, *args): def do_repourls(self, subcmd, opts, *args):
@ -1631,7 +1631,7 @@ Please submit there instead, or use --nodevelproject to force direct submission.
rev, dummy = parseRevisionOption(opts.revision) rev, dummy = parseRevisionOption(opts.revision)
if rev==None: if rev==None:
rev="latest" rev="latest"
if rev and rev != "latest" and not checkRevision(project, package, rev): if rev and rev != "latest" and not checkRevision(project, package, rev):
print >>sys.stderr, 'Revision \'%s\' does not exist' % rev print >>sys.stderr, 'Revision \'%s\' does not exist' % rev
@ -1827,7 +1827,7 @@ Please submit there instead, or use --nodevelproject to force direct submission.
continue continue
# ignore foo.rXX, foo.mine for files which are in 'C' state # ignore foo.rXX, foo.mine for files which are in 'C' state
if os.path.splitext(filename)[0] in p.in_conflict: if os.path.splitext(filename)[0] in p.in_conflict:
continue continue
state = p.status(filename) state = p.status(filename)
if state == '?': if state == '?':
@ -2063,8 +2063,8 @@ Please submit there instead, or use --nodevelproject to force direct submission.
side only. This is needed for removing the entire project. side only. This is needed for removing the entire project.
As a safety measure, projects must be empty (i.e., you need to delete all As a safety measure, projects must be empty (i.e., you need to delete all
packages first). packages first).
If you are sure that you want to remove a package and all If you are sure that you want to remove a package and all
its files use \'--force\' switch. Sometimes this also works without --force. its files use \'--force\' switch. Sometimes this also works without --force.
@ -2098,11 +2098,11 @@ Please submit there instead, or use --nodevelproject to force direct submission.
if not p.todo: if not p.todo:
prj_dir, pac_dir = getPrjPacPaths(p.absdir) prj_dir, pac_dir = getPrjPacPaths(p.absdir)
if is_project_dir(prj_dir): if is_project_dir(prj_dir):
if conf.config['do_package_tracking']: if conf.config['do_package_tracking']:
prj = Project(prj_dir, False) prj = Project(prj_dir, False)
prj.delPackage(p, opts.force) prj.delPackage(p, opts.force)
else: else:
print "WARNING: package tracking is disabled, operation skipped !" print "WARNING: package tracking is disabled, operation skipped !"
else: else:
pathn = getTransActPath(p.dir) pathn = getTransActPath(p.dir)
for filename in p.todo: for filename in p.todo:
@ -2483,9 +2483,9 @@ Please submit there instead, or use --nodevelproject to force direct submission.
help='Delete old build root before initializing it') help='Delete old build root before initializing it')
@cmdln.option('--no-changelog', action='store_true', @cmdln.option('--no-changelog', action='store_true',
help='don\'t update the package changelog from a changes file') help='don\'t update the package changelog from a changes file')
@cmdln.option('--rsync-src', metavar='RSYNCSRCPATH', dest='rsyncsrc', @cmdln.option('--rsync-src', metavar='RSYNCSRCPATH', dest='rsyncsrc',
help='Copy folder to buildroot after installing all RPMs. Use together with --rsync-dest. This is the path on the HOST filesystem e.g. /tmp/linux-kernel-tree. It defines RSYNCDONE 1 .') help='Copy folder to buildroot after installing all RPMs. Use together with --rsync-dest. This is the path on the HOST filesystem e.g. /tmp/linux-kernel-tree. It defines RSYNCDONE 1 .')
@cmdln.option('--rsync-dest', metavar='RSYNCDESTPATH', dest='rsyncdest', @cmdln.option('--rsync-dest', metavar='RSYNCDESTPATH', dest='rsyncdest',
help='Copy folder to buildroot after installing all RPMs. Use together with --rsync-src. This is the path on the TARGET filesystem e.g. /usr/src/packages/BUILD/linux-2.6 .') help='Copy folder to buildroot after installing all RPMs. Use together with --rsync-src. This is the path on the TARGET filesystem e.g. /usr/src/packages/BUILD/linux-2.6 .')
@cmdln.option('--overlay', metavar='OVERLAY', @cmdln.option('--overlay', metavar='OVERLAY',
help='Copy overlay filesystem to buildroot after installing all RPMs .') help='Copy overlay filesystem to buildroot after installing all RPMs .')
@ -2678,20 +2678,20 @@ Please submit there instead, or use --nodevelproject to force direct submission.
""" """
if len(args) == 4: if len(args) == 4:
apiurl = conf.config['apiurl'] apiurl = conf.config['apiurl']
project = args[0] project = args[0]
package = args[1] package = args[1]
repository = args[2] repository = args[2]
arch = args[3] arch = args[3]
elif len(args) == 2: elif len(args) == 2:
wd = os.curdir wd = os.curdir
package = store_read_package(wd) package = store_read_package(wd)
project = store_read_project(wd) project = store_read_project(wd)
repository = args[0] repository = args[0]
arch = args[1] arch = args[1]
apiurl = store_read_apiurl(wd) apiurl = store_read_apiurl(wd)
else: else:
raise oscerr.WrongArgs('Wrong number of arguments') raise oscerr.WrongArgs('Wrong number of arguments')
format = 'text' format = 'text'
if opts.csv: if opts.csv:
@ -2951,14 +2951,14 @@ Please submit there instead, or use --nodevelproject to force direct submission.
architecture = args[3] architecture = args[3]
elif len(args) == 2: elif len(args) == 2:
if is_package_dir(os.getcwd()): if is_package_dir(os.getcwd()):
project = Project(os.getcwd()).name project = Project(os.getcwd()).name
p = Package(os.getcwd()) p = Package(os.getcwd())
package = p.name package = p.name
apiurl = p.apiurl apiurl = p.apiurl
repository = args[0] repository = args[0]
architecture = args[1] architecture = args[1]
else: else:
sys.exit('Local directory is no checkout package, neither it is specified. ' ) sys.exit('Local directory is no checkout package, neither it is specified. ' )
else: else:
sys.exit('Need either 2 or 4 arguments.' ) sys.exit('Need either 2 or 4 arguments.' )
@ -3011,7 +3011,7 @@ Please submit there instead, or use --nodevelproject to force direct submission.
osc my rq osc my ... requests (osc req list -a -B) osc my rq osc my ... requests (osc req list -a -B)
${cmd_option_list} ${cmd_option_list}
'osc my' implements memonic shorthands for 'osc my' implements memonic shorthands for
specific 'osc search' and 'osc req list' commands. specific 'osc search' and 'osc req list' commands.
See there for additional help. See there for additional help.
""" """
@ -3019,14 +3019,13 @@ Please submit there instead, or use --nodevelproject to force direct submission.
if not args: if not args:
raise oscerr.WrongArgs('Please specify one of projects/packages/requests') raise oscerr.WrongArgs('Please specify one of projects/packages/requests')
if args[0] in ('requests', 'request', 'req', 'rq', if args[0] in ('requests', 'request', 'req', 'rq', 'submitrequest', 'submitreq', 'submit', 'sr'):
'submitrequest', 'submitreq', 'submit', 'sr'):
## FIXME: involvement bugowner is not reported here. ## FIXME: involvement bugowner is not reported here.
## this only reports usernames found in request history. ## this only reports usernames found in request history.
opts.state = 'all' opts.state = 'all'
opts.type = '' opts.type = ''
if args[0] in ('submitrequest', 'submitreq', 'submit', 'sr'): if args[0] in ('submitrequest', 'submitreq', 'submit', 'sr'):
opts.type = 'submit' opts.type = 'submit'
opts.days = conf.config['request_list_days'] opts.days = conf.config['request_list_days']
opts.mine = False opts.mine = False
opts.bugowner = True opts.bugowner = True
@ -3090,14 +3089,14 @@ Please submit there instead, or use --nodevelproject to force direct submission.
osc se ... osc se ...
${cmd_option_list} ${cmd_option_list}
osc search does not find binary rpm names. Use osc search does not find binary rpm names. Use
http://software.opensuse.org/search?q=binaryname http://software.opensuse.org/search?q=binaryname
""" """
if opts.mine: if opts.mine:
opts.bugowner = True opts.bugowner = True
opts.package = True opts.package = True
for_user = False for_user = False
if opts.involved or opts.bugowner or opts.maintainer: if opts.involved or opts.bugowner or opts.maintainer:
for_user = True for_user = True
@ -3161,9 +3160,9 @@ Please submit there instead, or use --nodevelproject to force direct submission.
## ##
## search used to report the table as ## search used to report the table as
## 'package project', I see no reason for having package before project. ## 'package project', I see no reason for having package before project.
## But it definitly hinders copy-paste. ## But it definitly hinders copy-paste.
## Changed to more normal 'project package' ordering. 2009-10-05, jw ## Changed to more normal 'project package' ordering. 2009-10-05, jw
## ##
for j, i in l: for j, i in l:
result.extend([j, i]) result.extend([j, i])
@ -3422,17 +3421,17 @@ Please submit there instead, or use --nodevelproject to force direct submission.
m = show_package_meta(conf.config['apiurl'], prj, pac) m = show_package_meta(conf.config['apiurl'], prj, pac)
tree = ET.parse(StringIO(''.join(m))) tree = ET.parse(StringIO(''.join(m)))
if not opts.nodevelproject and not opts.delete and not opts.add: if not opts.nodevelproject and not opts.delete and not opts.add:
while tree.findall('devel'): while tree.findall('devel'):
d = tree.find('devel') d = tree.find('devel')
prj = d.get('project', prj) prj = d.get('project', prj)
pac = d.get('package', pac) pac = d.get('package', pac)
print "Following to the development space:", prj, "/", pac print "Following to the development space:", prj, "/", pac
m = show_package_meta(conf.config['apiurl'], prj, pac) m = show_package_meta(conf.config['apiurl'], prj, pac)
tree = ET.parse(StringIO(''.join(m))) tree = ET.parse(StringIO(''.join(m)))
if not tree.findall('person'): if not tree.findall('person'):
print "No dedicated persons in package defined, showing the project persons !" print "No dedicated persons in package defined, showing the project persons !"
m = show_project_meta(conf.config['apiurl'], prj) m = show_project_meta(conf.config['apiurl'], prj)
tree = ET.parse(StringIO(''.join(m))) tree = ET.parse(StringIO(''.join(m)))
else: else:
raise oscerr.WrongArgs('I need at least one argument.') raise oscerr.WrongArgs('I need at least one argument.')
@ -3451,7 +3450,7 @@ Please submit there instead, or use --nodevelproject to force direct submission.
print role, ":" print role, ":"
for person in tree.findall('person'): for person in tree.findall('person'):
if person.get('role') == role: if person.get('role') == role:
maintainers.append(person.get('userid')) maintainers.append(person.get('userid'))
if opts.email: if opts.email:
emails = [] emails = []
@ -3492,12 +3491,12 @@ Please submit there instead, or use --nodevelproject to force direct submission.
if len(args) == 1 and (args[0].startswith('http://') or if len(args) == 1 and (args[0].startswith('http://') or
args[0].startswith('https://')): args[0].startswith('https://')):
opts.method = 'GET' opts.method = 'GET'
opts.headers = None opts.headers = None
opts.data = None opts.data = None
opts.file = None opts.file = None
return self.do_api('list', opts, *args) return self.do_api('list', opts, *args)
args = slash_split(args) args = slash_split(args)
@ -3533,7 +3532,7 @@ Please submit there instead, or use --nodevelproject to force direct submission.
This command checks out a package with merged source changes. It uses This command checks out a package with merged source changes. It uses
a 3-way merge to resolve file conflicts. After reviewing/repairing a 3-way merge to resolve file conflicts. After reviewing/repairing
the merge, use 'osc resolved ...' and 'osc ci' to re-create a the merge, use 'osc resolved ...' and 'osc ci' to re-create a
working source link. working source link.
usage: usage:
@ -3555,7 +3554,7 @@ Please submit there instead, or use --nodevelproject to force direct submission.
package = target_package = args[1] package = target_package = args[1]
target_prj = args[2] target_prj = args[2]
if len(args) == 4: if len(args) == 4:
target_package = args[3] target_package = args[3]
elif len(args) == 2: elif len(args) == 2:
target_prj = prj = args[0] target_prj = prj = args[0]
target_package = package = args[1] target_package = package = args[1]
@ -3656,8 +3655,8 @@ Please submit there instead, or use --nodevelproject to force direct submission.
os.chdir(destdir) os.chdir(destdir)
init_package_dir(apiurl, target_prj, target_package, destdir, files=False) init_package_dir(apiurl, target_prj, target_package, destdir, files=False)
os.chdir(olddir) os.chdir(olddir)
store_write_string(destdir, '_files', ''.join(meta)); store_write_string(destdir, '_files', ''.join(meta))
store_write_string(destdir, '_linkrepair', ''); store_write_string(destdir, '_linkrepair', '')
pac = Package(destdir) pac = Package(destdir)
storedir = os.path.join(destdir, store) storedir = os.path.join(destdir, store)
@ -3741,7 +3740,7 @@ Please submit there instead, or use --nodevelproject to force direct submission.
osc signkey [--create|--delete] <PROJECT> osc signkey [--create|--delete] <PROJECT>
This command is for managing gpg keys. It shows the public key This command is for managing gpg keys. It shows the public key
by default. There is no way to download or upload the private by default. There is no way to download or upload the private
part of a key by design. part of a key by design.
However you can create a new own key. You may want to consider However you can create a new own key. You may want to consider
@ -3768,14 +3767,14 @@ Please submit there instead, or use --nodevelproject to force direct submission.
raise oscerr.WrongArgs('Please specify just the project') raise oscerr.WrongArgs('Please specify just the project')
if opts.create: if opts.create:
url = makeurl(apiurl, ['source', prj], query='cmd=createkey') url = makeurl(apiurl, ['source', prj], query='cmd=createkey')
f = http_POST(url) f = http_POST(url)
elif opts.delete: elif opts.delete:
url = makeurl(apiurl, ['source', prj, "_pubkey"]) url = makeurl(apiurl, ['source', prj, "_pubkey"])
f = http_DELETE(url) f = http_DELETE(url)
else: else:
url = makeurl(apiurl, ['source', prj, "_pubkey"]) url = makeurl(apiurl, ['source', prj, "_pubkey"])
f = http_GET(url) f = http_GET(url)
while 1: while 1:
buf = f.read(16384) buf = f.read(16384)

View File

@ -6,11 +6,11 @@
"""Read osc configuration and store it in a dictionary """Read osc configuration and store it in a dictionary
This module reads and parses ~/.oscrc. The resulting configuration is stored This module reads and parses ~/.oscrc. The resulting configuration is stored
for later usage in a dictionary named 'config'. for later usage in a dictionary named 'config'.
The .oscrc is kept mode 0600, so that it is not publically readable. The .oscrc is kept mode 0600, so that it is not publically readable.
This gives no real security for storing passwords. This gives no real security for storing passwords.
If in doubt, use your favourite keyring. If in doubt, use your favourite keyring.
Password is stored on ~/.oscrc as bz2 compressed and base64 encoded, so that is fairly Password is stored on ~/.oscrc as bz2 compressed and base64 encoded, so that is fairly
large and not to be recognized or remembered easily by an occasional spectator. large and not to be recognized or remembered easily by an occasional spectator.
If information is missing, it asks the user questions. If information is missing, it asks the user questions.
@ -45,18 +45,18 @@ try:
GENERIC_KEYRING = True GENERIC_KEYRING = True
except: except:
try: try:
import gobject import gobject
gobject.set_application_name('osc') gobject.set_application_name('osc')
import gnomekeyring import gnomekeyring
if os.environ['GNOME_DESKTOP_SESSION_ID']: if os.environ['GNOME_DESKTOP_SESSION_ID']:
# otherwise gnome keyring bindings spit out errors, when you have # otherwise gnome keyring bindings spit out errors, when you have
# it installed, but you are not under gnome # it installed, but you are not under gnome
# (even though hundreds of gnome-keyring daemons got started in parallel) # (even though hundreds of gnome-keyring daemons got started in parallel)
# another option would be to support kwallet here # another option would be to support kwallet here
GNOME_KEYRING = gnomekeyring.is_available() GNOME_KEYRING = gnomekeyring.is_available()
except: except:
pass pass
DEFAULTS = { 'apiurl': 'https://api.opensuse.org', DEFAULTS = { 'apiurl': 'https://api.opensuse.org',
'user': 'your_username', 'user': 'your_username',
@ -93,7 +93,7 @@ DEFAULTS = { 'apiurl': 'https://api.opensuse.org',
# local files to ignore with status, addremove, .... # local files to ignore with status, addremove, ....
# local files to ignore with status, addremove, .... # local files to ignore with status, addremove, ....
'exclude_glob': '.osc CVS .svn .* _linkerror *~ #*# *.orig *.bak', 'exclude_glob': '.osc CVS .svn .* _linkerror *~ #*# *.orig *.bak',
# keep passwords in plaintext. If you see this comment, your osc # keep passwords in plaintext. If you see this comment, your osc
# already uses the encrypted password, and only keeps them in plain text # already uses the encrypted password, and only keeps them in plain text
# for backwards compatibility. Default will change to 0 in future releases. # for backwards compatibility. Default will change to 0 in future releases.
'plaintext_passwd': '1', 'plaintext_passwd': '1',
@ -278,7 +278,7 @@ def verify_cb(ok, store):
if(not ok): if(not ok):
err = store.get_error() err = store.get_error()
cert = store.get_current_cert() cert = store.get_current_cert()
print "*** Certificate verify failed (depth=%s) ***" % store.get_error_depth() print "*** Certificate verify failed (depth=%s) ***" % store.get_error_depth()
print "Subject: ", cert.get_subject() print "Subject: ", cert.get_subject()
print "Issuer: ", cert.get_issuer() print "Issuer: ", cert.get_issuer()
print "Fingerprint: ", cert.get_fingerprint() print "Fingerprint: ", cert.get_fingerprint()
@ -337,7 +337,7 @@ def init_basicauth(config):
cookie_file = os.path.expanduser(config['cookiejar']) cookie_file = os.path.expanduser(config['cookiejar'])
cookiejar = cookielib.LWPCookieJar(cookie_file) cookiejar = cookielib.LWPCookieJar(cookie_file)
try: try:
cookiejar.load(ignore_discard=True) cookiejar.load(ignore_discard=True)
except IOError: except IOError:
try: try:
@ -361,7 +361,7 @@ def init_basicauth(config):
if ctx.load_verify_locations(capath=capath, cafile=cafile) != 1: raise Exception('No CA certificates found') if ctx.load_verify_locations(capath=capath, cafile=cafile) != 1: raise Exception('No CA certificates found')
opener = m2urllib2.build_opener(ctx, urllib2.HTTPCookieProcessor(cookiejar), authhandler) opener = m2urllib2.build_opener(ctx, urllib2.HTTPCookieProcessor(cookiejar), authhandler)
else: else:
import sys; import sys
print >>sys.stderr, "WARNING: SSL certificate checks disabled. Connection is insecure!\n" print >>sys.stderr, "WARNING: SSL certificate checks disabled. Connection is insecure!\n"
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar), authhandler) opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar), authhandler)
@ -478,10 +478,10 @@ def add_section(filename, url, user, passwd):
if file: file.close() if file: file.close()
def get_config(override_conffile = None, def get_config(override_conffile = None,
override_apiurl = None, override_apiurl = None,
override_debug = None, override_debug = None,
override_http_debug = None, override_http_debug = None,
override_traceback = None, override_traceback = None,
override_post_mortem = None, override_post_mortem = None,
override_no_keyring = None, override_no_keyring = None,
@ -526,7 +526,7 @@ def get_config(override_conffile = None,
re_clist = re.compile('[, ]+') re_clist = re.compile('[, ]+')
config['extra-pkgs'] = [ i.strip() for i in re_clist.split(config['extra-pkgs'].strip()) if i ] config['extra-pkgs'] = [ i.strip() for i in re_clist.split(config['extra-pkgs'].strip()) if i ]
if config['extra-pkgs'] == []: if config['extra-pkgs'] == []:
config['extra-pkgs'] = None config['extra-pkgs'] = None
# collect the usernames, passwords and additional options for each api host # collect the usernames, passwords and additional options for each api host
@ -581,10 +581,10 @@ def get_config(override_conffile = None,
passwordx = cp.get(url, 'passx', raw=True) # especially on password! passwordx = cp.get(url, 'passx', raw=True) # especially on password!
if password is None or password == 'your_password': if password is None or password == 'your_password':
try: try:
password = passwordx.decode('base64').decode('bz2'); password = passwordx.decode('base64').decode('bz2')
except: except:
print "%s: no credentials known" % url print "%s: no credentials known" % url
password = 'your_password' password = 'your_password'
else: else:
if not passwordx: if not passwordx:
print "%s: rewriting from plain pass to encoded pass\n" % url print "%s: rewriting from plain pass to encoded pass\n" % url
@ -640,7 +640,8 @@ def get_config(override_conffile = None,
# override values which we were called with # override values which we were called with
if override_verbose: if override_verbose:
config['verbose'] = override_verbose + 1 config['verbose'] = override_verbose + 1
if not config.has_key('verbose') : config['verbose'] = 1; if not config.has_key('verbose'):
config['verbose'] = 1
if override_debug: if override_debug:
config['debug'] = override_debug config['debug'] = override_debug

File diff suppressed because it is too large Load Diff

View File

@ -17,7 +17,7 @@ except:
def join_url(self, base_url, rel_url): def join_url(self, base_url, rel_url):
"""to override _join_url of MirrorGroup, because we want to """to override _join_url of MirrorGroup, because we want to
pass full URLs instead of base URL where relative_url is added later... pass full URLs instead of base URL where relative_url is added later...
IOW, we make MirrorGroup ignore relative_url""" IOW, we make MirrorGroup ignore relative_url"""
return base_url return base_url
@ -67,8 +67,8 @@ class Fetcher:
# for use by the failure callback # for use by the failure callback
self.curpac = pac self.curpac = pac
if self.offline: if self.offline:
return True return True
MirrorGroup._join_url = join_url MirrorGroup._join_url = join_url
mg = MirrorGroup(self.gr, pac.urllist) mg = MirrorGroup(self.gr, pac.urllist)
@ -81,7 +81,7 @@ class Fetcher:
try: try:
# it returns the filename # it returns the filename
ret = mg.urlgrab(pac.filename, ret = mg.urlgrab(pac.filename,
filename = pac.fullpartname, filename = pac.fullpartname,
text = '(%s) %s' %(pac.project, pac.filename)) text = '(%s) %s' %(pac.project, pac.filename))
@ -109,7 +109,7 @@ class Fetcher:
pac.filename = canonname pac.filename = canonname
pac.fullfilename = os.path.join(pac.localdir, canonname) pac.fullfilename = os.path.join(pac.localdir, canonname)
os.rename(pac.fullpartname, pac.fullfilename); os.rename(pac.fullpartname, pac.fullfilename)
def dirSetup(self, pac): def dirSetup(self, pac):
dir = os.path.join(self.cachedir, pac.localdir) dir = os.path.join(self.cachedir, pac.localdir)
@ -143,7 +143,7 @@ class Fetcher:
def verify_pacs(pac_list): def verify_pacs(pac_list):
"""Take a list of rpm filenames and run rpm -K on them. """Take a list of rpm filenames and run rpm -K on them.
In case of failure, exit. In case of failure, exit.
@ -154,7 +154,7 @@ def verify_pacs(pac_list):
if not pac_list: if not pac_list:
return return
# don't care about the return value because we check the # don't care about the return value because we check the
# output anyway, and rpm always writes to stdout. # output anyway, and rpm always writes to stdout.
@ -166,19 +166,19 @@ def verify_pacs(pac_list):
stderr=subprocess.STDOUT, close_fds=True).stdout stderr=subprocess.STDOUT, close_fds=True).stdout
# restore locale # restore locale
if saved_LC_ALL: os.environ['LC_ALL'] = saved_LC_ALL; if saved_LC_ALL: os.environ['LC_ALL'] = saved_LC_ALL
else: os.environ.pop('LC_ALL') else: os.environ.pop('LC_ALL')
for line in o.readlines(): for line in o.readlines():
if not 'OK' in line: if not 'OK' in line:
print print
print >>sys.stderr, 'The following package could not be verified:' print >>sys.stderr, 'The following package could not be verified:'
print >>sys.stderr, line print >>sys.stderr, line
sys.exit(1) sys.exit(1)
if 'NOT OK' in line: if 'NOT OK' in line:
print print
print >>sys.stderr, 'The following package could not be verified:' print >>sys.stderr, 'The following package could not be verified:'
print >>sys.stderr, line print >>sys.stderr, line
@ -198,7 +198,7 @@ def verify_pacs(pac_list):
- If you do not trust the packages, you should configure osc build for XEN or KVM - If you do not trust the packages, you should configure osc build for XEN or KVM
- You may use --no-verify to skip the verification (which is a risk for your system). - You may use --no-verify to skip the verification (which is a risk for your system).
""" % {'name': missing_key, """ % {'name': missing_key,
'dir': os.path.expanduser('~')} 'dir': os.path.expanduser('~')}
else: else:

View File

@ -9,12 +9,12 @@
# Lesser General Public License for more details. # Lesser General Public License for more details.
# #
# You should have received a copy of the GNU Lesser General Public # You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the # License along with this library; if not, write to the
# Free Software Foundation, Inc., # Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, # 59 Temple Place, Suite 330,
# Boston, MA 02111-1307 USA # Boston, MA 02111-1307 USA
# this is basically a copy of python-urlgrabber's TextMeter class, # this is basically a copy of python-urlgrabber's TextMeter class,
# with support added for dynamical sizing according to screen size. # with support added for dynamical sizing according to screen size.
# it uses getScreenWidth() scrapped from smart. # it uses getScreenWidth() scrapped from smart.
# 2007-04-24, poeml # 2007-04-24, poeml
@ -22,7 +22,7 @@
from urlgrabber.progress import BaseMeter, format_time, format_number from urlgrabber.progress import BaseMeter, format_time, format_number
import sys, os import sys, os
def getScreenWidth(): def getScreenWidth():
import termios, struct, fcntl import termios, struct, fcntl
s = struct.pack('HHHH', 0, 0, 0, 0) s = struct.pack('HHHH', 0, 0, 0, 0)

View File

@ -17,15 +17,15 @@ class UserAbort(OscBaseError):
class ConfigError(OscBaseError): class ConfigError(OscBaseError):
"""Exception raised when there is an error in the config file""" """Exception raised when there is an error in the config file"""
def __init__(self, msg, file): def __init__(self, msg, fname):
OscBaseError.__init__(self) OscBaseError.__init__(self)
self.msg = msg self.msg = msg
self.file = file self.file = fname
class ConfigMissingApiurl(ConfigError): class ConfigMissingApiurl(ConfigError):
"""Exception raised when a apiurl does not exist in the config file""" """Exception raised when a apiurl does not exist in the config file"""
def __init__(self, msg, file, url): def __init__(self, msg, fname, url):
ConfigError.__init__(self, msg, file) ConfigError.__init__(self, msg, fname)
self.url = url self.url = url
class APIError(OscBaseError): class APIError(OscBaseError):
@ -60,7 +60,7 @@ class WorkingCopyWrongVersion(OscBaseError):
class WorkingCopyOutdated(OscBaseError): class WorkingCopyOutdated(OscBaseError):
"""Exception raised when the working copy is outdated. """Exception raised when the working copy is outdated.
It takes a tuple with three arguments: path to wc, It takes a tuple with three arguments: path to wc,
revision that it has, revision that it should have. revision that it has, revision that it should have.
""" """
def __str__(self): def __str__(self):
@ -92,7 +92,7 @@ class SignalInterrupt(Exception):
class PackageExists(PackageError): class PackageExists(PackageError):
""" """
Exception raised when a local object already exists Exception raised when a local object already exists
""" """
def __init__(self, prj, pac, msg): def __init__(self, prj, pac, msg):
PackageError.__init__(self, prj, pac) PackageError.__init__(self, prj, pac)

View File

@ -1,14 +1,14 @@
# Copyright 2009 Marcus Huewe <suse-tux@gmx.de> # Copyright 2009 Marcus Huewe <suse-tux@gmx.de>
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 2 # modify it under the terms of the GNU General Public License version 2
# as published by the Free Software Foundation; # as published by the Free Software Foundation;
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA

View File

@ -1,14 +1,14 @@
# Copyright 2009 Marcus Huewe <suse-tux@gmx.de> # Copyright 2009 Marcus Huewe <suse-tux@gmx.de>
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 2 # modify it under the terms of the GNU General Public License version 2
# as published by the Free Software Foundation; # as published by the Free Software Foundation;
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
@ -231,13 +231,13 @@ class CpioWrite:
c.append('\0' * (len(''.join(c)) % 4)) c.append('\0' * (len(''.join(c)) % 4))
c.append(content) c.append(content)
c = ''.join(c) c = ''.join(c)
if len(c) % 4: if len(c) % 4:
c += '\0' * (4 - len(c) % 4) c += '\0' * (4 - len(c) % 4)
self.cpio += c self.cpio += c
def add_padding(self): def add_padding(self):
if len(self.cpio) % 512: if len(self.cpio) % 512:
self.cpio += '\0' * (512 - len(self.cpio) % 512) self.cpio += '\0' * (512 - len(self.cpio) % 512)

View File

@ -8,7 +8,6 @@
# 2008-03-25, jw, v0.3 -- go via api using iChains and ~/.oscrc # 2008-03-25, jw, v0.3 -- go via api using iChains and ~/.oscrc
# 2008-03-26, jw, v0.4 -- added linked file retrieval and usage. # 2008-03-26, jw, v0.4 -- added linked file retrieval and usage.
use Data::Dumper; use Data::Dumper;
use LWP::UserAgent; use LWP::UserAgent;
use HTTP::Status; use HTTP::Status;
@ -34,7 +33,7 @@ my $cfg = {
@ISA = qw(LWP::UserAgent); @ISA = qw(LWP::UserAgent);
sub new sub new
{ {
my $self = LWP::UserAgent::new(@_); my $self = LWP::UserAgent::new(@_);
$self->agent("osc_expand_link.pl/$version"); $self->agent("osc_expand_link.pl/$version");
$self; $self;
@ -46,20 +45,20 @@ my $cfg = {
unless ($self->{auth}) unless ($self->{auth})
{ {
print STDERR "Auth for $realm at $netloc\n"; print STDERR "Auth for $realm at $netloc\n";
unless (open IN, "<", "$ENV{HOME}/.oscrc") unless (open IN, "<", "$ENV{HOME}/.oscrc")
{ {
print STDERR "$ENV{HOME}/.oscrc: $!\n"; print STDERR "$ENV{HOME}/.oscrc: $!\n";
return (undef, undef); return (undef, undef);
} }
while (defined (my $line = <IN>)) while (defined (my $line = <IN>))
{ {
chomp $line; chomp $line;
$self->{auth}{pass} = $1 if $line =~ m{^pass\s*=\s*(\S+)}; $self->{auth}{pass} = $1 if $line =~ m{^pass\s*=\s*(\S+)};
$self->{auth}{user} = $1 if $line =~ m{^user\s*=\s*(\S+)}; $self->{auth}{user} = $1 if $line =~ m{^user\s*=\s*(\S+)};
} }
close IN; close IN;
print STDERR "~/.oscrc: user=$self->{auth}{user}\n"; print STDERR "~/.oscrc: user=$self->{auth}{user}\n";
} }
return ($self->{auth}{user},$self->{auth}{pass}); return ($self->{auth}{user},$self->{auth}{pass});
} }
@ -99,7 +98,7 @@ if (my $url = $ARGV[0])
die qq{osc_expand_link $version; die qq{osc_expand_link $version;
Usage: Usage:
osc co $cfg->{project} $cfg->{package} osc co $cfg->{project} $cfg->{package}
cd $cfg->{project}/$cfg->{package} cd $cfg->{project}/$cfg->{package}
@ -127,30 +126,30 @@ to retrieve the original specfile behind a link.
if ($url =~ m{^(.*/)?linked/(.*)$}) if ($url =~ m{^(.*/)?linked/(.*)$})
{ {
$url = (defined $1) ? $1 : "$cfg->{project}/$cfg->{package}"; $url = (defined $1) ? $1 : "$cfg->{project}/$cfg->{package}";
my $file = $2; my $file = $2;
$url = "$source/$url" if $cfg->{apiurl} and $url !~ m{://}; $url = "$source/$url" if $cfg->{apiurl} and $url !~ m{://};
print STDERR "$url\n"; print STDERR "$url\n";
my $dir = xml_parse(cred_get($url), 'merge'); my $dir = xml_parse(cred_get($url), 'merge');
my $li = $dir->{directory}{linkinfo} || die "no linkinfo in $url\n"; my $li = $dir->{directory}{linkinfo} || die "no linkinfo in $url\n";
$url = "$source/$li->{project}/$li->{package}"; $url = "$source/$li->{project}/$li->{package}";
mkdir("linked"); mkdir("linked");
if ($file =~ m{\*}) if ($file =~ m{\*})
{ {
my $dir = xml_parse(cred_get($url), 'merge'); my $dir = xml_parse(cred_get($url), 'merge');
$dir = $dir->{directory} if $dir->{directory}; $dir = $dir->{directory} if $dir->{directory};
my @list = sort map { $_->{name} } @{$dir->{entry}}; my @list = sort map { $_->{name} } @{$dir->{entry}};
my $file_re = "\Q$file\E"; $file_re =~ s{\\\*}{\.\*}g; my $file_re = "\Q$file\E"; $file_re =~ s{\\\*}{\.\*}g;
my @match = grep { $_ =~ m{^$file_re$} } @list; my @match = grep { $_ =~ m{^$file_re$} } @list;
die "pattern $file not found in\n @list\n" unless @match; die "pattern $file not found in\n @list\n" unless @match;
$file = $match[0]; $file = $match[0];
} }
$url .= "/$file"; $url .= "/$file";
print STDERR "$url -> linked/$file\n"; print STDERR "$url -> linked/$file\n";
my $r = cred_getstore($url, "linked/$file"); my $r = cred_getstore($url, "linked/$file");
print STDERR " Error: $r\n" if $r != RC_OK; print STDERR " Error: $r\n" if $r != RC_OK;
exit 0; exit 0;
} }
$url = "$cfg->{project}/$cfg->{package}/$url" unless $url =~ m{/}; $url = "$cfg->{project}/$cfg->{package}/$url" unless $url =~ m{/};
@ -179,19 +178,19 @@ for my $file (@{$dir->{entry}})
if (-f $file->{name}) if (-f $file->{name})
{ {
## check the md5sum of the existing file and be happy. ## check the md5sum of the existing file and be happy.
$md5 = Digest::MD5->new; $md5 = Digest::MD5->new;
open IN, "<", $file->{name} or die "md5sum($file->{name} failed: $!"; open IN, "<", $file->{name} or die "md5sum($file->{name} failed: $!";
$md5->addfile(*IN); $md5->addfile(*IN);
close IN; close IN;
if ($md5->hexdigest eq $file->{md5}) if ($md5->hexdigest eq $file->{md5})
{ {
print STDERR " - $file->{name} (md5 unchanged)\n"; print STDERR " - $file->{name} (md5 unchanged)\n";
} }
else else
{ {
print STDERR "Modified: $file->{name}, please commit changes!\n"; print STDERR "Modified: $file->{name}, please commit changes!\n";
} }
next; next;
} }
print STDERR " get $file->{name}"; print STDERR " get $file->{name}";
# fixme: xsrcmd5 is obsolete. # fixme: xsrcmd5 is obsolete.
@ -216,10 +215,10 @@ sub slurp_file
## xml parser imported from w3dcm.pl and somewhat expanded. ## xml parser imported from w3dcm.pl and somewhat expanded.
## 2006-12-15, jw ## 2006-12-15, jw
## ##
## xml_parse assumes correct container closing. ## xml_parse assumes correct container closing.
## Any </...> tag would closes an open <foo>. ## Any </...> tag would closes an open <foo>.
## Thus xml_parse is not suitable for HTML. ## Thus xml_parse is not suitable for HTML.
## ##
sub xml_parse sub xml_parse
{ {
my ($text, $attr) = @_; my ($text, $attr) = @_;
@ -236,13 +235,13 @@ sub xml_parse
my $s = $tags[$i]->{offset} + $tags[$i]->{tag_len}; my $s = $tags[$i]->{offset} + $tags[$i]->{tag_len};
if (defined $tags[$i+1]) if (defined $tags[$i+1])
{ {
my $l = $tags[$i+1]->{offset} - $s; my $l = $tags[$i+1]->{offset} - $s;
$cdata = substr $text, $s, $l; $cdata = substr $text, $s, $l;
} }
else else
{ {
$cdata = substr $text, $s; $cdata = substr $text, $s;
} }
# print "tag=$tag\n"; # print "tag=$tag\n";
my $name = $1 if $tag =~ s{<([\?/]?[\w:-]+)\s*}{}; my $name = $1 if $tag =~ s{<([\?/]?[\w:-]+)\s*}{};
@ -256,29 +255,29 @@ sub xml_parse
xml_add_attr($x, $tag, $attr) unless $tag eq ''; xml_add_attr($x, $tag, $attr) unless $tag eq '';
if (!$close) if (!$close)
{ {
delete $t->{-cdata} if $t->{-cdata} and $t->{-cdata} =~ m{^\s*$}; delete $t->{-cdata} if $t->{-cdata} and $t->{-cdata} =~ m{^\s*$};
unless ($t->{$name}) unless ($t->{$name})
{ {
$t->{$name} = $x; $t->{$name} = $x;
} }
else else
{ {
$t->{$name} = [ $t->{$name} ] unless ref $t->{$name} eq 'ARRAY'; $t->{$name} = [ $t->{$name} ] unless ref $t->{$name} eq 'ARRAY';
push @{$t->{$name}}, $x; push @{$t->{$name}}, $x;
} }
} }
if ($close) if ($close)
{ {
$t = pop @stack; $t = pop @stack;
} }
elsif ($nest) elsif ($nest)
{ {
push @stack, $t; push @stack, $t;
$t = $x; $t = $x;
} }
} }
print "stack=", Data::Dumper::Dumper(\@stack) if $verbose > 2; print "stack=", Data::Dumper::Dumper(\@stack) if $verbose > 2;
@ -305,7 +304,7 @@ sub xml_slurp_file
$xml = xml_parse($xml, $opt->{attr}); $xml = xml_parse($xml, $opt->{attr});
if (my $container = $opt->{container}) if (my $container = $opt->{container})
{ {
die "xml_slurp($file, '$container') malformed file, should have only one toplevel node.\n" die "xml_slurp($file, '$container') malformed file, should have only one toplevel node.\n"
unless scalar keys %$xml == 1; unless scalar keys %$xml == 1;
$container = (keys %$xml)[0] if $container eq '' or $container eq '*'; $container = (keys %$xml)[0] if $container eq '' or $container eq '*';
die "xml_slurp($file, '$container') toplevel tag missing or wrong.\n" unless $xml->{$container}; die "xml_slurp($file, '$container') toplevel tag missing or wrong.\n" unless $xml->{$container};
@ -360,36 +359,35 @@ sub scalar_cdata
my $val = $hash->{$key}; my $val = $hash->{$key};
if (ref $val eq 'ARRAY') if (ref $val eq 'ARRAY')
{ {
for my $i (0..$#$val) for my $i (0..$#$val)
{ {
scalar_cdata($hash->{$key}[$i]); scalar_cdata($hash->{$key}[$i]);
} }
} }
elsif (ref $val eq 'HASH') elsif (ref $val eq 'HASH')
{ {
my @k = keys %$val; my @k = keys %$val;
if (scalar(@k) == 1 && ($k[0] eq '-cdata')) if (scalar(@k) == 1 && ($k[0] eq '-cdata'))
{ {
$hash->{$key} = $hash->{$key}{-cdata}; $hash->{$key} = $hash->{$key}{-cdata};
} }
else else
{ {
delete $hash->{$key}{-cdata} if exists $val->{-cdata} && $val->{-cdata} =~ m{^\s*$}; delete $hash->{$key}{-cdata} if exists $val->{-cdata} && $val->{-cdata} =~ m{^\s*$};
scalar_cdata($hash->{$key}); scalar_cdata($hash->{$key});
} }
} }
} }
delete $hash->{$selftag}; delete $hash->{$selftag};
} }
## ##
## find_tags -- a brute force tag finder. ## find_tags -- a brute force tag finder.
## This code is robust enough to parse the weirdest HTML. ## This code is robust enough to parse the weirdest HTML.
## An Array containing hashes of { offset, name, tag_len } is returned. ## An Array containing hashes of { offset, name, tag_len } is returned.
## CDATA is skipped, but can be determined from gaps between tags. ## CDATA is skipped, but can be determined from gaps between tags.
## The name parser may chop names, so XML-style tag names are ## The name parser may chop names, so XML-style tag names are
## unreliable. ## unreliable.
## ##
sub find_tags sub find_tags
{ {
@ -405,39 +403,39 @@ sub find_tags
if ($inquotes) if ($inquotes)
{ {
$inquotes = 0 if $what eq '"'; $inquotes = 0 if $what eq '"';
next; next;
} }
if ($incomment) if ($incomment)
{ {
$incomment = 0 if $what eq '-->'; $incomment = 0 if $what eq '-->';
next; next;
} }
if ($what eq '"') if ($what eq '"')
{ {
$inquotes = 1; $inquotes = 1;
next; next;
} }
if ($what eq '<!--') if ($what eq '<!--')
{ {
$incomment = 1; $incomment = 1;
next; next;
} }
next if $what eq $last; # opening and closing angular brackets are polar. next if $what eq $last; # opening and closing angular brackets are polar.
if ($what eq '>' and scalar @tags) if ($what eq '>' and scalar @tags)
{ {
$tags[$#tags]{tag_len} = 1 + $offset - $tags[$#tags]{offset}; $tags[$#tags]{tag_len} = 1 + $offset - $tags[$#tags]{offset};
} }
if ($what eq '<') if ($what eq '<')
{ {
push @tags, {name => $name, offset => $offset }; push @tags, {name => $name, offset => $offset };
} }
$last = $what; $last = $what;
} }
@ -447,7 +445,7 @@ sub find_tags
## ##
## how = undef: defaults to '-attr plain' ## how = undef: defaults to '-attr plain'
## how = '-attr plain': add the attributes as one scalar value to hash-element -attr ## how = '-attr plain': add the attributes as one scalar value to hash-element -attr
## how = '-attr hash': add the attributes as a hash-ref to hash-element -attr ## how = '-attr hash': add the attributes as a hash-ref to hash-element -attr
## how = 'merge': add the attributes as direct hash elements. (This is irreversible) ## how = 'merge': add the attributes as direct hash elements. (This is irreversible)
## ##
## attributes are either space-separated, or delimited with '' or "". ## attributes are either space-separated, or delimited with '' or "".
@ -470,22 +468,20 @@ sub xml_add_attr
{ {
while ($text =~ m{([\w_:-]+)\s*=("[^"]*"|'[^']'|\S*)\s*}g) while ($text =~ m{([\w_:-]+)\s*=("[^"]*"|'[^']'|\S*)\s*}g)
{ {
my ($key, $val) = ($1, $2); my ($key, $val) = ($1, $2);
$val =~ s{^"(.*)"$}{$1} unless $val =~ s{^'(.*)'$}{$1}; $val =~ s{^"(.*)"$}{$1} unless $val =~ s{^'(.*)'$}{$1};
if (defined($hash->{$key})) if (defined($hash->{$key}))
{ {
## redefinition. promote to array and push. ## redefinition. promote to array and push.
$hash->{$key} = [ $hash->{$key} ] unless ref $hash->{$key}; $hash->{$key} = [ $hash->{$key} ] unless ref $hash->{$key};
push @{$hash->{$key}}, $val; push @{$hash->{$key}}, $val;
} }
else else
{ {
$hash->{$key} = $val; $hash->{$key} = $val;
} }
} }
return $hash; return $hash;
} }
die "xml_expand_attr: unknown method '$how'\n"; die "xml_expand_attr: unknown method '$how'\n";
} }
#################################################################

View File

@ -15,7 +15,7 @@ if __name__ == '__main__':
try: try:
prof = hotshot.Profile(filename) prof = hotshot.Profile(filename)
prof.runcall(commandline.main) prof.runcall(commandline.main)
print 'run complete. analyzing.' print 'run complete. analyzing.'
prof.close() prof.close()

View File

@ -13,7 +13,7 @@ from osc import commandline
chdir = os.chdir chdir = os.chdir
mkdir = os.mkdir mkdir = os.mkdir
# here, all tests will happen... # here, all tests will happen...
BASEDIR = os.path.join(os.getcwd(), 't') BASEDIR = os.path.join(os.getcwd(), 't')
PRJ = 'home:poeml' PRJ = 'home:poeml'
@ -41,7 +41,7 @@ def checkout_and_clean(self):
class TestOsc(unittest.TestCase): class TestOsc(unittest.TestCase):
def setUp(self): def setUp(self):
if not os.path.isabs(BASEDIR): if not os.path.isabs(BASEDIR):
@ -221,7 +221,7 @@ class TestOsc(unittest.TestCase):
self.assertEqual(self.err, '') self.assertEqual(self.err, '')
self.assertEqual(self.out, 'M foo\n') self.assertEqual(self.out, 'M foo\n')
# from wc1, commit a change # from wc1, commit a change
chdir(wc1) chdir(wc1)
open('foo', 'a').write("""geht aus""") open('foo', 'a').write("""geht aus""")
runosc('ci') runosc('ci')
@ -236,15 +236,15 @@ class TestOsc(unittest.TestCase):
self.assertEqual(self.err, '') self.assertEqual(self.err, '')
self.assertEqual(self.out, 'M foo\n') self.assertEqual(self.out, 'M foo\n')
# successful merge is one thing, but checking the local modification # successful merge is one thing, but checking the local modification
# makes sure that the store copy has been updated to the upstream revision # makes sure that the store copy has been updated to the upstream revision
self.out, self.err = runosc('diff') self.out, self.err = runosc('diff')
self.assertEqual(self.err, '') self.assertEqual(self.err, '')
expected = dedent("""\ expected = dedent("""\
Index: foo Index: foo
=================================================================== ===================================================================
--- foo (revision XX) --- foo (revision XX)
+++ foo (working copy) +++ foo (working copy)
@@ -1,4 +1,4 @@ @@ -1,4 +1,4 @@
-ein -ein
+kein +kein
@ -342,7 +342,7 @@ Committed revision XX.
self.out, self.err = runosc('ci -m msg') self.out, self.err = runosc('ci -m msg')
self.assertEqual(self.err, '') self.assertEqual(self.err, '')
self.assertEqual(remove_revid(self.out), """Deleting foo1 self.assertEqual(remove_revid(self.out), """Deleting foo1
Transmitting file data Transmitting file data
Committed revision XX. Committed revision XX.
""") """)
@ -472,7 +472,7 @@ def runcmd(cmd, argstring):
def touch(filename): def touch(filename):
open(filename, 'w').close(); open(filename, 'w').close()
if __name__ == '__main__': if __name__ == '__main__':