[MediaWiki-commits] [Gerrit] Make Recentchanges be able to return all revisions - change (pywikibot/compat)

2014-02-28 Thread Nullzero (Code Review)
Nullzero has uploaded a new change for review.

  https://gerrit.wikimedia.org/r/116218

Change subject: Make Recentchanges be able to return all revisions
..

Make Recentchanges be able to return all revisions

Recentchanges() is supposed to be able to return all revisions.
This patch therefore adds a parameter to return all revisions.
The default value for this parameter, however, is to return distinct
pages, in order to keep backward-compatibility.

Bug: 55152
Change-Id: I958be12e1a197a00e197f0746c7ee47960fb952e
---
M wikipedia.py
1 file changed, 11 insertions(+), 3 deletions(-)


  git pull ssh://gerrit.wikimedia.org:29418/pywikibot/compat 
refs/changes/18/116218/1

diff --git a/wikipedia.py b/wikipedia.py
index 45880cc..84230f7 100644
--- a/wikipedia.py
+++ b/wikipedia.py
@@ -8155,7 +8155,7 @@
 def recentchanges(self, number=100, rcstart=None, rcend=None, rcshow=None,
   rcdir='older', rctype='edit|new', namespace=None,
   includeredirects=True, repeat=False, user=None,
-  returndict=False, nobots=False):
+  returndict=False, nobots=False, redirect=False):
 """
 Yield recent changes as Page objects
 uses API call:
@@ -8200,6 +8200,9 @@
 timestamp (unicode), length (int), an empty unicode string, username
 or IP address (str), comment (unicode).
 
+If parameter revision is true, this function returns distinct
+revisions. If false, it returns only distinct pages.
+
 # TODO: Detection of unregistered users is broken
 """
 if rctype is None:
@@ -8231,6 +8234,11 @@
 if rctype:
 params['rctype'] = rctype
 
+if revision:
+keyseen = 'revid'
+else:
+keyseen = 'pageid'
+
 seen = set()
 while True:
 data = query.GetData(params, self)
@@ -8243,8 +8251,8 @@
 "The APIs don't return data, the site may be down")
 
 for i in rcData:
-if i['pageid'] not in seen:
-seen.add(i['pageid'])
+if i[keyseen] not in seen:
+seen.add(i[keyseen])
 page = Page(self, i['title'], defaultNamespace=i['ns'])
 if 'comment' in i:
 page._comment = i['comment']

-- 
To view, visit https://gerrit.wikimedia.org/r/116218
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: newchange
Gerrit-Change-Id: I958be12e1a197a00e197f0746c7ee47960fb952e
Gerrit-PatchSet: 1
Gerrit-Project: pywikibot/compat
Gerrit-Branch: master
Gerrit-Owner: Nullzero 

___
MediaWiki-commits mailing list
MediaWiki-commits@lists.wikimedia.org
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits


[MediaWiki-commits] [Gerrit] Prevent Special:Diff from processing empty string - change (mediawiki/core)

2014-02-22 Thread Nullzero (Code Review)
Nullzero has uploaded a new change for review.

  https://gerrit.wikimedia.org/r/114944

Change subject: Prevent Special:Diff from processing empty string
..

Prevent Special:Diff from processing empty string

Umherirrender found that I77fdaf8e has a flaw. Currently it is possible
to go to index.php?title=Special:Diff (without any trailing string),
and the page will be redirected to index.php?diff= which is the last diff
of the main page. However, the intended way to deal with this case is to
raise ErrorPageError. This patch fixes the problem.

Change-Id: I3ff0b11671f27e77d9068930338ec8bbb674a89f
---
M includes/specials/SpecialDiff.php
1 file changed, 1 insertion(+), 1 deletion(-)


  git pull ssh://gerrit.wikimedia.org:29418/mediawiki/core 
refs/changes/44/114944/1

diff --git a/includes/specials/SpecialDiff.php 
b/includes/specials/SpecialDiff.php
index bc0d7e3..77d2317 100644
--- a/includes/specials/SpecialDiff.php
+++ b/includes/specials/SpecialDiff.php
@@ -46,7 +46,7 @@
$parts = explode( '/', $subpage );
 
// Try to parse the values given, generating somewhat pretty 
URLs if possible
-   if ( count( $parts ) === 1 ) {
+   if ( count( $parts ) === 1 && $parts[0] !== '' ) {
$this->mAddedRedirectParams['diff'] = $parts[0];
} elseif ( count( $parts ) === 2 ) {
$this->mAddedRedirectParams['oldid'] = $parts[0];

-- 
To view, visit https://gerrit.wikimedia.org/r/114944
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: newchange
Gerrit-Change-Id: I3ff0b11671f27e77d9068930338ec8bbb674a89f
Gerrit-PatchSet: 1
Gerrit-Project: mediawiki/core
Gerrit-Branch: master
Gerrit-Owner: Nullzero 

___
MediaWiki-commits mailing list
MediaWiki-commits@lists.wikimedia.org
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits


[MediaWiki-commits] [Gerrit] Fix and rewrite PageGenerator's query string - change (pywikibot/core)

2014-02-22 Thread Nullzero (Code Review)
Nullzero has uploaded a new change for review.

  https://gerrit.wikimedia.org/r/114949

Change subject: Fix and rewrite PageGenerator's query string
..

Fix and rewrite PageGenerator's query string

The old code has a flaw when, for example, iiprop is in kwargs. Instead of
"xxx|timestamp|...", the query string will be "xxxtimestamp|..."
which is wrong. This patch fixes the problem and remove redundancy
of the code.

Change-Id: I7d496a612d32c70ccb53d2cdcf95cc036944d808
---
M pywikibot/data/api.py
1 file changed, 11 insertions(+), 18 deletions(-)


  git pull ssh://gerrit.wikimedia.org:29418/pywikibot/core 
refs/changes/49/114949/1

diff --git a/pywikibot/data/api.py b/pywikibot/data/api.py
index a574935..45c5d04 100644
--- a/pywikibot/data/api.py
+++ b/pywikibot/data/api.py
@@ -769,27 +769,20 @@
 version of each Page (default False)
 
 """
+def appendParams(params, key, value):
+if key in params:
+params[key] += '|' + value
+else:
+params[key] = value
 # get some basic information about every page generated
-if 'prop' in kwargs:
-kwargs['prop'] += "|info|imageinfo|categoryinfo"
-else:
-kwargs['prop'] = 'info|imageinfo|categoryinfo'
+appendParams(kwargs, 'prop', 'info|imageinfo|categoryinfo')
 if g_content:
 # retrieve the current revision
-kwargs['prop'] += "|revisions"
-if "rvprop" in kwargs:
-kwargs["rvprop"] += "ids|timestamp|flags|comment|user|content"
-else:
-kwargs["rvprop"] = "ids|timestamp|flags|comment|user|content"
-if "inprop" in kwargs:
-if "protection" not in kwargs["inprop"]:
-kwargs["inprop"] += "|protection"
-else:
-kwargs['inprop'] = 'protection'
-if "iiprop" in kwargs:
-kwargs["iiprop"] += 'timestamp|user|comment|url|size|sha1|metadata'
-else:
-kwargs['iiprop'] = 'timestamp|user|comment|url|size|sha1|metadata'
+appendParams(kwargs, 'prop', 'revisions')
+appendParams(kwargs, 'rvprop', 
'ids|timestamp|flags|comment|user|content')
+if not ('inprop' in kwargs and 'protection' in kwargs['inprop']):
+appendParams(kwargs, 'inprop', 'protection')
+appendParams(kwargs, 'iiprop', 
'timestamp|user|comment|url|size|sha1|metadata')
 QueryGenerator.__init__(self, generator=generator, **kwargs)
 self.resultkey = "pages"  # element to look for in result
 

-- 
To view, visit https://gerrit.wikimedia.org/r/114949
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: newchange
Gerrit-Change-Id: I7d496a612d32c70ccb53d2cdcf95cc036944d808
Gerrit-PatchSet: 1
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Nullzero 

___
MediaWiki-commits mailing list
MediaWiki-commits@lists.wikimedia.org
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits


[MediaWiki-commits] [Gerrit] Implement expiry in protect() - change (pywikibot/core)

2014-02-24 Thread Nullzero (Code Review)
Nullzero has uploaded a new change for review.

  https://gerrit.wikimedia.org/r/115177

Change subject: Implement expiry in protect()
..

Implement expiry in protect()

This patch implements a way to set the duration of protection, like
that in block().

Change-Id: I4981f4f094c082ce75ae2973b581bdc3063b10ee
---
M pywikibot/page.py
M pywikibot/site.py
2 files changed, 9 insertions(+), 3 deletions(-)


  git pull ssh://gerrit.wikimedia.org:29418/pywikibot/core 
refs/changes/77/115177/1

diff --git a/pywikibot/page.py b/pywikibot/page.py
index b75bbc3..f633cb2 100644
--- a/pywikibot/page.py
+++ b/pywikibot/page.py
@@ -1411,7 +1411,7 @@
 
 @deprecate_arg("throttle", None)
 def protect(self, edit='sysop', move='sysop', unprotect=False,
-reason=None, prompt=True):
+reason=None, prompt=True, expiry=None):
 """(Un)protect a wiki page. Requires administrator status.
 
 Valid protection levels (in MediaWiki 1.12) are '' (equivalent to
@@ -1423,6 +1423,7 @@
 all protection levels to '')
 @param reason: Edit summary.
 @param prompt: If true, ask user for confirmation.
+@param expiry: When the block should expire
 
 """
 if reason is None:
@@ -1447,7 +1448,7 @@
 answer = 'y'
 self.site._noProtectPrompt = True
 if answer in ['y', 'Y']:
-return self.site.protect(self, edit, move, reason)
+return self.site.protect(self, edit, move, reason, expiry)
 
 def change_category(self, oldCat, newCat, comment=None, sortKey=None,
 inPlace=True):
diff --git a/pywikibot/site.py b/pywikibot/site.py
index 3d85c6b..8824a06 100644
--- a/pywikibot/site.py
+++ b/pywikibot/site.py
@@ -3099,7 +3099,7 @@
 }
 
 @must_be(group='sysop')
-def protect(self, page, edit, move, summary):
+def protect(self, page, edit, move, summary, expiry=None):
 """(Un)protect a wiki page. Requires administrator status.
 
 Valid protection levels (in MediaWiki 1.12) are '' (equivalent to
@@ -3111,6 +3111,7 @@
 all protection levels to '')
 @param reason: Edit summary.
 @param prompt: If true, ask user for confirmation.
+@param expiry: When the block should expire
 
 """
 token = self.token(page, "protect")
@@ -3119,6 +3120,10 @@
   title=page.title(withSection=False),
   protections="edit=" + edit + "|" + "move=" + move,
   reason=summary)
+if isinstance(expiry, pywikibot.Timestamp):
+expiry = expiry.toISOformat()
+if expiry:
+req['expiry'] = expiry
 try:
 result = req.submit()
 except api.APIError as err:

-- 
To view, visit https://gerrit.wikimedia.org/r/115177
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: newchange
Gerrit-Change-Id: I4981f4f094c082ce75ae2973b581bdc3063b10ee
Gerrit-PatchSet: 1
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Nullzero 

___
MediaWiki-commits mailing list
MediaWiki-commits@lists.wikimedia.org
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits


[MediaWiki-commits] [Gerrit] Make list=allfileusages functional - change (mediawiki/core)

2014-02-05 Thread Nullzero (Code Review)
Nullzero has uploaded a new change for review.

  https://gerrit.wikimedia.org/r/111734

Change subject: Make list=allfileusages functional
..

Make list=allfileusages functional

Querying list=allfileusages with affrom, afto, or afunique
will always get afinvalidtitle because the code passes the namespace
wrongly. This patch fixes the problem.

Change-Id: I010dc3a03be74f49902fd446e7dbc306c16b869c
---
M includes/api/ApiQueryAllLinks.php
1 file changed, 3 insertions(+), 3 deletions(-)


  git pull ssh://gerrit.wikimedia.org:29418/mediawiki/core 
refs/changes/34/111734/1

diff --git a/includes/api/ApiQueryAllLinks.php 
b/includes/api/ApiQueryAllLinks.php
index 13f766e..bccc25f 100644
--- a/includes/api/ApiQueryAllLinks.php
+++ b/includes/api/ApiQueryAllLinks.php
@@ -149,14 +149,14 @@
 
// 'continue' always overrides 'from'
$from = ( $continue || $params['from'] === null ? null :
-   $this->titlePartToKey( $params['from'], 
$params['namespace'] ) );
+   $this->titlePartToKey( $params['from'], $namespace ) );
$to = ( $params['to'] === null ? null :
-   $this->titlePartToKey( $params['to'], 
$params['namespace'] ) );
+   $this->titlePartToKey( $params['to'], $namespace ) );
$this->addWhereRange( $pfx . $fieldTitle, 'newer', $from, $to );
 
if ( isset( $params['prefix'] ) ) {
$this->addWhere( $pfx . $fieldTitle . $db->buildLike( 
$this->titlePartToKey(
-   $params['prefix'], $params['namespace'] ), 
$db->anyString() ) );
+   $params['prefix'], $namespace ), 
$db->anyString() ) );
}
 
$this->addFields( array( 'pl_title' => $pfx . $fieldTitle ) );

-- 
To view, visit https://gerrit.wikimedia.org/r/111734
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: newchange
Gerrit-Change-Id: I010dc3a03be74f49902fd446e7dbc306c16b869c
Gerrit-PatchSet: 1
Gerrit-Project: mediawiki/core
Gerrit-Branch: master
Gerrit-Owner: Nullzero 

___
MediaWiki-commits mailing list
MediaWiki-commits@lists.wikimedia.org
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits


[MediaWiki-commits] [Gerrit] Make Recentchanges return all revisions - change (pywikibot/compat)

2014-02-06 Thread Nullzero (Code Review)
Nullzero has uploaded a new change for review.

  https://gerrit.wikimedia.org/r/111832

Change subject: Make Recentchanges return all revisions
..

Make Recentchanges return all revisions

Recentchanges() is supposed to return all revisions, but now it returns
only pages which the program hasn't detected before. This patch solves
the problem.

bug: 55152
Change-Id: I0fe918cc21f3912ecb5f7189a8001c3c73d31fd0
---
M wikipedia.py
1 file changed, 2 insertions(+), 2 deletions(-)


  git pull ssh://gerrit.wikimedia.org:29418/pywikibot/compat 
refs/changes/32/111832/1

diff --git a/wikipedia.py b/wikipedia.py
index 86d4f23..a8a3fc6 100644
--- a/wikipedia.py
+++ b/wikipedia.py
@@ -8243,8 +8243,8 @@
 "The APIs don't return data, the site may be down")
 
 for i in rcData:
-if i['pageid'] not in seen:
-seen.add(i['pageid'])
+if i['revid'] not in seen:
+seen.add(i['revid'])
 page = Page(self, i['title'], defaultNamespace=i['ns'])
 if 'comment' in i:
 page._comment = i['comment']

-- 
To view, visit https://gerrit.wikimedia.org/r/111832
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: newchange
Gerrit-Change-Id: I0fe918cc21f3912ecb5f7189a8001c3c73d31fd0
Gerrit-PatchSet: 1
Gerrit-Project: pywikibot/compat
Gerrit-Branch: master
Gerrit-Owner: Nullzero 

___
MediaWiki-commits mailing list
MediaWiki-commits@lists.wikimedia.org
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits


[MediaWiki-commits] [Gerrit] Support editing as a sysop - change (pywikibot/core)

2014-02-06 Thread Nullzero (Code Review)
Nullzero has uploaded a new change for review.

  https://gerrit.wikimedia.org/r/111943

Change subject: Support editing as a sysop
..

Support editing as a sysop

This patch makes all functions which are decorated with
must_be('user') can perform with sysop account if the function
is called with parameter sysop=True

Bug: 58789
Change-Id: Ib8df98667b9457504f54de856aa4c4db0a997635
---
M pywikibot/site.py
1 file changed, 11 insertions(+), 8 deletions(-)


  git pull ssh://gerrit.wikimedia.org:29418/pywikibot/core 
refs/changes/43/111943/1

diff --git a/pywikibot/site.py b/pywikibot/site.py
index 20ee4bb..05de86a 100644
--- a/pywikibot/site.py
+++ b/pywikibot/site.py
@@ -707,16 +707,19 @@
 @returns: a decorator to make sure the requirement is statisfied when
   the decorated function is called.
 """
-if group == 'user':
-run = lambda self: self.login(False)
-elif group == 'sysop':
-run = lambda self: self.login(True)
-else:
-raise Exception("Not implemented")
-
 def decorator(fn):
 def callee(self, *args, **kwargs):
-run(self)
+grp = group
+if 'sysop' in kwargs:
+if kwargs['sysop']:
+grp = 'sysop'
+del kwargs['sysop']
+if grp == 'user':
+self.login(False)
+elif grp == 'sysop':
+self.login(True)
+else:
+raise Exception("Not implemented")
 return fn(self, *args, **kwargs)
 callee.__name__ = fn.__name__
 callee.__doc__ = fn.__doc__

-- 
To view, visit https://gerrit.wikimedia.org/r/111943
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: newchange
Gerrit-Change-Id: Ib8df98667b9457504f54de856aa4c4db0a997635
Gerrit-PatchSet: 1
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Nullzero 

___
MediaWiki-commits mailing list
MediaWiki-commits@lists.wikimedia.org
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits


[MediaWiki-commits] [Gerrit] Switch sysop parameter to as_group='sysop' - change (pywikibot/core)

2014-02-08 Thread Nullzero (Code Review)
Nullzero has uploaded a new change for review.

  https://gerrit.wikimedia.org/r/112299

Change subject: Switch sysop parameter to as_group='sysop'
..

Switch sysop parameter to as_group='sysop'

Gerrit Ib8df9866 makes bot can switch to sysop account to edit pages
by using parameter "as_group='sysop'". This replaces parameter
"sysop=True" in compat. This patch therefore marks parameter
sysop as deprecated.

Bug: 58789
Change-Id: Ifccab04a63c8bc418ade7fafd795450a121e7c19
---
M pywikibot/page.py
1 file changed, 1 insertion(+), 0 deletions(-)


  git pull ssh://gerrit.wikimedia.org:29418/pywikibot/core 
refs/changes/99/112299/1

diff --git a/pywikibot/page.py b/pywikibot/page.py
index b75bbc3..f7556e1 100644
--- a/pywikibot/page.py
+++ b/pywikibot/page.py
@@ -785,6 +785,7 @@
 # no restricting template found
 return True
 
+@deprecate_arg('sysop', 'as_group="sysop"')
 def save(self, comment=None, watch=None, minor=True, botflag=None,
  force=False, async=False, callback=None, **kwargs):
 """Save the current contents of page's text to the wiki.

-- 
To view, visit https://gerrit.wikimedia.org/r/112299
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: newchange
Gerrit-Change-Id: Ifccab04a63c8bc418ade7fafd795450a121e7c19
Gerrit-PatchSet: 1
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Nullzero 

___
MediaWiki-commits mailing list
MediaWiki-commits@lists.wikimedia.org
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits


[MediaWiki-commits] [Gerrit] Make language of messages depend on site - change (pywikibot/core)

2014-02-10 Thread Nullzero (Code Review)
Nullzero has uploaded a new change for review.

  https://gerrit.wikimedia.org/r/112604

Change subject: Make language of messages depend on site
..

Make language of messages depend on site

Language of messages queried from allmessages depends on bot's setting
(see bug: 61119). However, APISite.mediawiki_messages() depends on
site object. This patch therefore makes mediawiki_messages()
retrieve the correct language.

Change-Id: I9c5a0b5b549822731247374140e44a79f09f33a5
---
M pywikibot/site.py
1 file changed, 1 insertion(+), 0 deletions(-)


  git pull ssh://gerrit.wikimedia.org:29418/pywikibot/core 
refs/changes/04/112604/1

diff --git a/pywikibot/site.py b/pywikibot/site.py
index bdf6618..3d85c6b 100644
--- a/pywikibot/site.py
+++ b/pywikibot/site.py
@@ -1011,6 +1011,7 @@
 site=self,
 meta="allmessages",
 ammessages='|'.join(keys),
+amlang=self.lang,
 )
 
 # Return all messages

-- 
To view, visit https://gerrit.wikimedia.org/r/112604
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: newchange
Gerrit-Change-Id: I9c5a0b5b549822731247374140e44a79f09f33a5
Gerrit-PatchSet: 1
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Nullzero 

___
MediaWiki-commits mailing list
MediaWiki-commits@lists.wikimedia.org
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits


[MediaWiki-commits] [Gerrit] Prevent NoSuchSite error from reading obsolete site's langua... - change (pywikibot/core)

2014-02-11 Thread Nullzero (Code Review)
Nullzero has uploaded a new change for review.

  https://gerrit.wikimedia.org/r/112842

Change subject: Prevent NoSuchSite error from reading obsolete site's language 
link
..

Prevent NoSuchSite error from reading obsolete site's language link

It's possible that a page will link to obsolete site.
As pywikibot tries to process these links, it will fail from
pywikibot.NoSuchSite. This patch solves the problem.

Bug: 61120
Change-Id: I3d6ef66c369da7f0b64b821d7d78454192601839
---
M pywikibot/data/api.py
M pywikibot/site.py
2 files changed, 14 insertions(+), 7 deletions(-)


  git pull ssh://gerrit.wikimedia.org:29418/pywikibot/core 
refs/changes/42/112842/1

diff --git a/pywikibot/data/api.py b/pywikibot/data/api.py
index a574935..ad24ca5 100644
--- a/pywikibot/data/api.py
+++ b/pywikibot/data/api.py
@@ -997,10 +997,14 @@
 if "langlinks" in pagedict:
 links = []
 for ll in pagedict["langlinks"]:
-link = pywikibot.Link.langlinkUnsafe(ll['lang'],
- ll['*'],
- source=page.site)
-links.append(link)
+try:
+link = pywikibot.Link.langlinkUnsafe(ll['lang'],
+ ll['*'],
+ source=page.site)
+except pywikibot.NoSuchSite:
+pass
+else:
+links.append(link)
 
 if hasattr(page, "_langlinks"):
 page._langlinks.extend(links)
diff --git a/pywikibot/site.py b/pywikibot/site.py
index 3d85c6b..2f34563 100644
--- a/pywikibot/site.py
+++ b/pywikibot/site.py
@@ -1974,9 +1974,12 @@
 if 'langlinks' not in pageitem:
 continue
 for linkdata in pageitem['langlinks']:
-yield pywikibot.Link.langlinkUnsafe(linkdata['lang'],
-linkdata['*'],
-source=self)
+try:
+yield pywikibot.Link.langlinkUnsafe(linkdata['lang'],
+linkdata['*'],
+source=self)
+except pywikibot.NoSuchSite:
+pass
 
 def page_extlinks(self, page, step=None, total=None):
 """Iterate all external links on page, yielding URL strings."""

-- 
To view, visit https://gerrit.wikimedia.org/r/112842
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: newchange
Gerrit-Change-Id: I3d6ef66c369da7f0b64b821d7d78454192601839
Gerrit-PatchSet: 1
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Nullzero 

___
MediaWiki-commits mailing list
MediaWiki-commits@lists.wikimedia.org
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits


[MediaWiki-commits] [Gerrit] Fix delete and switch to using must_be - change (pywikibot/core)

2014-01-24 Thread Nullzero (Code Review)
Nullzero has uploaded a new change for review.

  https://gerrit.wikimedia.org/r/109339


Change subject: Fix delete and switch to using must_be
..

Fix delete and switch to using must_be

This patch follows Merlijn van Deen's suggestion to use must_be
instead of calling APISite.login directly. It also fixes Page.delete
to support switching between bot and sysop account and consequently
partially fixes bug:60278.

Change-Id: Ibc94da881fce312f42ce58fd9a440d1fb5e06109
---
M pywikibot/page.py
M pywikibot/site.py
2 files changed, 3 insertions(+), 15 deletions(-)


  git pull ssh://gerrit.wikimedia.org:29418/pywikibot/core 
refs/changes/39/109339/1

diff --git a/pywikibot/page.py b/pywikibot/page.py
index 2949fa2..91d2038 100644
--- a/pywikibot/page.py
+++ b/pywikibot/page.py
@@ -1294,7 +1294,7 @@
 pywikibot.output(u'Deleting %s.' % (self.title(asLink=True)))
 reason = pywikibot.input(u'Please enter a reason for the 
deletion:')
 
-if self.site.logged_in(sysop=True):  # If user is a sysop, delete the 
page
+if self.site.username(sysop=True):  # If user is a sysop, delete the 
page
 answer = u'y'
 if prompt and not hasattr(self.site, '_noDeletePrompt'):
 answer = pywikibot.inputChoice(
diff --git a/pywikibot/site.py b/pywikibot/site.py
index 3048834..a4e8d19 100644
--- a/pywikibot/site.py
+++ b/pywikibot/site.py
@@ -3026,6 +3026,7 @@
 "cantdelete": "Could not delete [[%(title)s]]. Maybe it was deleted 
already.",
 }  # other errors shouldn't occur because of pre-submission checks
 
+@must_be(group='sysop')
 def deletepage(self, page, summary):
 """Delete page from the wiki. Requires appropriate privilege level.
 
@@ -3033,13 +3034,6 @@
 @param summary: Edit summary (required!).
 
 """
-try:
-self.login(sysop=True)
-except pywikibot.NoUsername as e:
-raise NoUsername("delete: Unable to login as sysop (%s)"
- % e.__class__.__name__)
-if not self.logged_in(sysop=True):
-raise NoUsername("delete: Unable to login as sysop")
 token = self.token(page, "delete")
 self.lock_page(page)
 req = api.Request(site=self, action="delete", token=token,
@@ -3070,6 +3064,7 @@
 "protect-invalidlevel": "Invalid protection level"
 }
 
+@must_be(group='sysop')
 def protect(self, page, edit, move, summary):
 """(Un)protect a wiki page. Requires administrator status.
 
@@ -3084,13 +3079,6 @@
 @param prompt: If true, ask user for confirmation.
 
 """
-try:
-self.login(sysop=True)
-except pywikibot.NoUsername as e:
-raise NoUsername("protect: Unable to login as sysop (%s)"
- % e.__class__.__name__)
-if not self.logged_in(sysop=True):
-raise NoUsername("protect: Unable to login as sysop")
 token = self.token(page, "protect")
 self.lock_page(page)
 req = api.Request(site=self, action="protect", token=token,

-- 
To view, visit https://gerrit.wikimedia.org/r/109339
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: newchange
Gerrit-Change-Id: Ibc94da881fce312f42ce58fd9a440d1fb5e06109
Gerrit-PatchSet: 1
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Nullzero 

___
MediaWiki-commits mailing list
MediaWiki-commits@lists.wikimedia.org
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits


[MediaWiki-commits] [Gerrit] Preload abusefilter-warning if created page is blank - change (mediawiki...AbuseFilter)

2014-01-26 Thread Nullzero (Code Review)
Nullzero has uploaded a new change for review.

  https://gerrit.wikimedia.org/r/109518


Change subject: Preload abusefilter-warning if created page is blank
..

Preload abusefilter-warning if created page is blank

This patch preloads MediaWiki:abusefilter-warning.
Generally, it will make users more convenient because filter warnings
usually have a pattern, and preloading a pattern from the page
will save time. This patch doesn't work when
MediaWiki:abusefilter-warning hasn't created yet.

Change-Id: Ia327463c52060bfd55c0a1fa6fcec592cc3c3999
---
M modules/ext.abuseFilter.edit.js
1 file changed, 1 insertion(+), 1 deletion(-)


  git pull ssh://gerrit.wikimedia.org:29418/mediawiki/extensions/AbuseFilter 
refs/changes/18/109518/1

diff --git a/modules/ext.abuseFilter.edit.js b/modules/ext.abuseFilter.edit.js
index b0ab8dd..1fbb7e6 100644
--- a/modules/ext.abuseFilter.edit.js
+++ b/modules/ext.abuseFilter.edit.js
@@ -210,7 +210,7 @@
function editWarnMessage() {
var message = getCurrentWarningMessage();
 
-   window.location = mw.config.get( 'wgScript' ) + 
'?title=MediaWiki:' +  mw.util.wikiUrlencode( message ) + '&action=edit';
+   window.location = mw.config.get( 'wgScript' ) + 
'?title=MediaWiki:' +  mw.util.wikiUrlencode( message ) + 
'&action=edit&preload=MediaWiki:abusefilter-warning';
}
 
/**

-- 
To view, visit https://gerrit.wikimedia.org/r/109518
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: newchange
Gerrit-Change-Id: Ia327463c52060bfd55c0a1fa6fcec592cc3c3999
Gerrit-PatchSet: 1
Gerrit-Project: mediawiki/extensions/AbuseFilter
Gerrit-Branch: master
Gerrit-Owner: Nullzero 

___
MediaWiki-commits mailing list
MediaWiki-commits@lists.wikimedia.org
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits


[MediaWiki-commits] [Gerrit] make MOVED_TO* working - change (mediawiki...AbuseFilter)

2013-12-30 Thread Nullzero (Code Review)
Nullzero has uploaded a new change for review.

  https://gerrit.wikimedia.org/r/104706


Change subject: make MOVED_TO* working
..

make MOVED_TO* working

This patch makes all variables of which prefix is MOVED_TO
functional again in AbuseFilter.

Bug: 52053
Change-Id: I6c5471620a0fb5cb78b946fc162ff3d6a30b0e0e
---
M AbuseFilter.class.php
1 file changed, 2 insertions(+), 2 deletions(-)


  git pull ssh://gerrit.wikimedia.org:29418/mediawiki/extensions/AbuseFilter 
refs/changes/06/104706/1

diff --git a/AbuseFilter.class.php b/AbuseFilter.class.php
index 24d9080..842697a 100644
--- a/AbuseFilter.class.php
+++ b/AbuseFilter.class.php
@@ -1974,10 +1974,10 @@
$user->setName( $row->rc_user_text );
}
 
-   $params = explode( "\n", trim( $row->rc_params ) );
+   $params = array_values(unserialize($row->rc_params));
 
$oldTitle = Title::makeTitle( $row->rc_namespace, 
$row->rc_title );
-   $newTitle = Title::newFromText( $params[0] );
+   $newTitle = Title::makeTitle( $params[1], $params[0] );
 
$vars = AbuseFilterVariableHolder::merge(
$vars,

-- 
To view, visit https://gerrit.wikimedia.org/r/104706
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: newchange
Gerrit-Change-Id: I6c5471620a0fb5cb78b946fc162ff3d6a30b0e0e
Gerrit-PatchSet: 1
Gerrit-Project: mediawiki/extensions/AbuseFilter
Gerrit-Branch: master
Gerrit-Owner: Nullzero 
Gerrit-Reviewer: jenkins-bot

___
MediaWiki-commits mailing list
MediaWiki-commits@lists.wikimedia.org
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits


[MediaWiki-commits] [Gerrit] LogEntry: Make newFromRow works with object - change (mediawiki/core)

2013-12-30 Thread Nullzero (Code Review)
Nullzero has uploaded a new change for review.

  https://gerrit.wikimedia.org/r/104708


Change subject: LogEntry: Make newFromRow works with object
..

LogEntry: Make newFromRow works with object

I am working on bug:52053 and solving this bug needs some
functions in DatabaseLogEntry/RCDatabaseLogEntry. However,
I found that if I pass an RCrow as an object to newFromRow
function, the function will treat the row as normal
DatabaseLogEntry, not RCDatabaseLogEntry. This bug will
fix the problem by converting row to object first and
determine whether row is RCDatabaseLogEntry or not later.

Change-Id: I6f64358837b37c54d00a7544e9e8a92c216bbe89
---
M includes/logging/LogEntry.php
1 file changed, 3 insertions(+), 2 deletions(-)


  git pull ssh://gerrit.wikimedia.org:29418/mediawiki/core 
refs/changes/08/104708/1

diff --git a/includes/logging/LogEntry.php b/includes/logging/LogEntry.php
index 76c2280..71b4fc2 100644
--- a/includes/logging/LogEntry.php
+++ b/includes/logging/LogEntry.php
@@ -161,8 +161,9 @@
 * @return DatabaseLogEntry
 */
public static function newFromRow( $row ) {
-   if ( is_array( $row ) && isset( $row['rc_logid'] ) ) {
-   return new RCDatabaseLogEntry( (object)$row );
+   $row = (object)$row;
+   if ( isset( $row->rc_logid ) ) {
+   return new RCDatabaseLogEntry( $row );
} else {
return new self( $row );
}

-- 
To view, visit https://gerrit.wikimedia.org/r/104708
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: newchange
Gerrit-Change-Id: I6f64358837b37c54d00a7544e9e8a92c216bbe89
Gerrit-PatchSet: 1
Gerrit-Project: mediawiki/core
Gerrit-Branch: master
Gerrit-Owner: Nullzero 

___
MediaWiki-commits mailing list
MediaWiki-commits@lists.wikimedia.org
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits


[MediaWiki-commits] [Gerrit] always show diff link if available - change (mediawiki...AbuseFilter)

2014-01-05 Thread Nullzero (Code Review)
Nullzero has uploaded a new change for review.

  https://gerrit.wikimedia.org/r/105637


Change subject: always show diff link if available
..

always show diff link if available

This patch makes a diff link appear in Special:Abuselog no matter a filter
is public or private. Because there is much information to figure out which
revision a filter catches, showing a diff link will make patrollers more
convenient without leaking more information. Note that when a filter
prevents an action, there will be no diff link. Since parser functions
are not available, a way to display correctly is to concatenate $diffLink
to $parsed_comments directly.

Bug: 59695
Change-Id: I6a4432cbb41ae78583cc87355514f252984c1005
---
M special/SpecialAbuseLog.php
1 file changed, 4 insertions(+), 0 deletions(-)


  git pull ssh://gerrit.wikimedia.org:29418/mediawiki/extensions/AbuseFilter 
refs/changes/37/105637/1

diff --git a/special/SpecialAbuseLog.php b/special/SpecialAbuseLog.php
index 96437c7..b3d89fa 100644
--- a/special/SpecialAbuseLog.php
+++ b/special/SpecialAbuseLog.php
@@ -530,6 +530,10 @@
$row->afl_user_text
)->parse();
} else {
+   if ($diffLink)
+   // concatenate strings, not increase the 
parameter (in AbuseFilter.i18n), because sometimes the link might not exist
+   $parsed_comments .= " ($diffLink)"; 
+   
$description = $this->msg( 'abusefilter-log-entry' 
)->rawParams(
$timestamp,
$userLink,

-- 
To view, visit https://gerrit.wikimedia.org/r/105637
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: newchange
Gerrit-Change-Id: I6a4432cbb41ae78583cc87355514f252984c1005
Gerrit-PatchSet: 1
Gerrit-Project: mediawiki/extensions/AbuseFilter
Gerrit-Branch: master
Gerrit-Owner: Nullzero 
Gerrit-Reviewer: jenkins-bot

___
MediaWiki-commits mailing list
MediaWiki-commits@lists.wikimedia.org
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits


[MediaWiki-commits] [Gerrit] Change the translation of th namespace - change (mediawiki...Scribunto)

2016-04-02 Thread Nullzero (Code Review)
Nullzero has uploaded a new change for review.

  https://gerrit.wikimedia.org/r/281118

Change subject: Change the translation of th namespace
..

Change the translation of th namespace

Change the translation of "Module" from "เกณฑ์สำหรับวัด" which is totally wrong 
and meaningless
to "โมดูล" which is the correct one. The consensus to modify this can be found 
at
https://th.wikipedia.org/wiki/วิกิพีเดีย:ศาลาชุมชน/อภิปราย/เปลี่ยนชื่อเนมสเปซ_module

This commit corrects [[gerrit:243617]].

Change-Id: I1eeb295c25a34c2852bc7c71921534b578b73e35
---
M Scribunto.namespaces.php
1 file changed, 2 insertions(+), 2 deletions(-)


  git pull ssh://gerrit.wikimedia.org:29418/mediawiki/extensions/Scribunto 
refs/changes/18/281118/1

diff --git a/Scribunto.namespaces.php b/Scribunto.namespaces.php
index 3dde283..eca47d9 100644
--- a/Scribunto.namespaces.php
+++ b/Scribunto.namespaces.php
@@ -378,8 +378,8 @@
 );
 
 $namespaceNames['th'] = array(
-   828 => 'เกณฑ์สำหรับวัด',
-   829 => 'โมดูลของการพูดคุย',
+   828 => 'มอดูล',
+   829 => 'คุยเรื่องมอดูล',
 );
 
 $namespaceNames['tr'] = array(

-- 
To view, visit https://gerrit.wikimedia.org/r/281118
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: newchange
Gerrit-Change-Id: I1eeb295c25a34c2852bc7c71921534b578b73e35
Gerrit-PatchSet: 1
Gerrit-Project: mediawiki/extensions/Scribunto
Gerrit-Branch: master
Gerrit-Owner: Nullzero 

___
MediaWiki-commits mailing list
MediaWiki-commits@lists.wikimedia.org
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits


[MediaWiki-commits] [Gerrit] Fix flake error - change (pywikibot/core)

2014-08-18 Thread Nullzero (Code Review)
Nullzero has uploaded a new change for review.

  https://gerrit.wikimedia.org/r/154837

Change subject: Fix flake error
..

Fix flake error

Change-Id: Id75c5da9970e41cf8700b46c59c094fc3790871e
---
M scripts/protect.py
1 file changed, 2 insertions(+), 1 deletion(-)


  git pull ssh://gerrit.wikimedia.org:29418/pywikibot/core 
refs/changes/37/154837/1

diff --git a/scripts/protect.py b/scripts/protect.py
index 256d76b..620d74f 100644
--- a/scripts/protect.py
+++ b/scripts/protect.py
@@ -219,7 +219,8 @@
 # set the default value for all
 # None (not the string 'none') will be ignored by Site.protect()
 combined_protections = dict([
-(p_type, default_level) for p_type in protection_types])
+(protection_type, default_level)
+for protection_type in protection_types])
 for p_type, level in protections.items():
 level = check_protection_level(p_type, level, protection_levels,
default_level)

-- 
To view, visit https://gerrit.wikimedia.org/r/154837
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: newchange
Gerrit-Change-Id: Id75c5da9970e41cf8700b46c59c094fc3790871e
Gerrit-PatchSet: 1
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Nullzero 

___
MediaWiki-commits mailing list
MediaWiki-commits@lists.wikimedia.org
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits


[MediaWiki-commits] [Gerrit] Revert "[IMPROV] Reduce usage of unicode()" - change (pywikibot/core)

2014-12-06 Thread Nullzero (Code Review)
Nullzero has uploaded a new change for review.

  https://gerrit.wikimedia.org/r/178005

Change subject: Revert "[IMPROV] Reduce usage of unicode()"
..

Revert "[IMPROV] Reduce usage of unicode()"

The change completely breaks:
https://travis-ci.org/wikimedia/pywikibot-core/builds/43211148

This reverts commit 58fd995ac73efa1c7807c0315c8c2140eb22011b.

Change-Id: I815faa4f75c2a473dfa444da9248607717e5288a
---
M pywikibot/bot.py
M pywikibot/pagegenerators.py
M scripts/checkimages.py
3 files changed, 17 insertions(+), 7 deletions(-)


  git pull ssh://gerrit.wikimedia.org:29418/pywikibot/core 
refs/changes/05/178005/1

diff --git a/pywikibot/bot.py b/pywikibot/bot.py
index 99622dc..6e92dbf 100644
--- a/pywikibot/bot.py
+++ b/pywikibot/bot.py
@@ -266,7 +266,7 @@
 log(u'=== Pywikibot framework v2.0 -- Logging header ===')
 
 # script call
-log(u'COMMAND: %s' % sys.argv)
+log(u'COMMAND: %s' % unicode(sys.argv))
 
 # script call time stamp
 log(u'DATE: %s UTC' % str(datetime.datetime.utcnow()))
@@ -280,7 +280,7 @@
 
 # system
 if hasattr(os, 'uname'):
-log(u'SYSTEM: %s' % os.uname())
+log(u'SYSTEM: %s' % unicode(os.uname()))
 
 # config file dir
 log(u'CONFIG FILE DIR: %s' % pywikibot.config2.base_dir)
@@ -319,7 +319,7 @@
 log(u'  %s' % ver)
 
 if config.log_pywiki_repo_version:
-log(u'PYWIKI REPO VERSION: %s' % version.getversion_onlinerepo())
+log(u'PYWIKI REPO VERSION: %s' % 
unicode(version.getversion_onlinerepo()))
 
 log(u'=== ' * 14)
 
@@ -1074,7 +1074,7 @@
 
 if site not in self._sites:
 log(u'LOADING SITE %s VERSION: %s'
-% (site, site.version()))
+% (site, unicode(site.version(
 
 self._sites.add(site)
 if len(self._sites) == 2:
diff --git a/pywikibot/pagegenerators.py b/pywikibot/pagegenerators.py
index 00e0f11..a4b5b43 100644
--- a/pywikibot/pagegenerators.py
+++ b/pywikibot/pagegenerators.py
@@ -40,6 +40,7 @@
 
 if sys.version_info[0] > 2:
 basestring = (str, )
+unicode = str
 
 _logger = "pagegenerators"
 
@@ -1965,7 +1966,7 @@
 
 pywikibot.output(u'retrieved %d items' % data[u'status'][u'items'])
 for item in data[u'items']:
-page = pywikibot.ItemPage(repo, u'Q{0}'.format(item))
+page = pywikibot.ItemPage(repo, u'Q' + unicode(item))
 try:
 link = page.getSitelink(site)
 except pywikibot.NoPage:
diff --git a/scripts/checkimages.py b/scripts/checkimages.py
index 66b1aee..1310359 100644
--- a/scripts/checkimages.py
+++ b/scripts/checkimages.py
@@ -92,6 +92,7 @@
 import re
 import time
 import datetime
+import locale
 import sys
 
 import pywikibot
@@ -101,6 +102,8 @@
 
 if sys.version_info[0] > 2:
 basestring = (str, )
+
+locale.setlocale(locale.LC_ALL, '')
 
 ###
 # <--- Change only below! --->#
@@ -569,8 +572,14 @@
 def printWithTimeZone(message):
 """Print the messages followed by the TimeZone encoded correctly."""
 if message[-1] != ' ':
-message = u'%s ' % message
-time_zone = time.strftime(u"%d %b %Y %H:%M:%S (UTC)", time.gmtime())
+message = '%s ' % unicode(message)
+if locale.getlocale()[1]:
+time_zone = unicode(time.strftime(u"%d %b %Y %H:%M:%S (UTC)",
+  time.gmtime()),
+locale.getlocale()[1])
+else:
+time_zone = unicode(time.strftime(u"%d %b %Y %H:%M:%S (UTC)",
+  time.gmtime()))
 pywikibot.output(u"%s%s" % (message, time_zone))
 
 

-- 
To view, visit https://gerrit.wikimedia.org/r/178005
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: newchange
Gerrit-Change-Id: I815faa4f75c2a473dfa444da9248607717e5288a
Gerrit-PatchSet: 1
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Nullzero 

___
MediaWiki-commits mailing list
MediaWiki-commits@lists.wikimedia.org
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits


[MediaWiki-commits] [Gerrit] Fix error because of passing too many parameters - change (pywikibot/core)

2014-01-14 Thread Nullzero (Code Review)
Nullzero has uploaded a new change for review.

  https://gerrit.wikimedia.org/r/107521


Change subject: Fix error because of passing too many parameters
..

Fix error because of passing too many parameters

Function delete_1_broken_redirect accepts just only one parameter,
but there is one line calling this function with two parameters,
consequently making an error. This patch trims the excessive parameter
so that the script will be functional again.

Change-Id: Ic3da077470b3358081ed8ffd85ef774d74837d40
---
M scripts/redirect.py
1 file changed, 1 insertion(+), 1 deletion(-)


  git pull ssh://gerrit.wikimedia.org:29418/pywikibot/core 
refs/changes/21/107521/1

diff --git a/scripts/redirect.py b/scripts/redirect.py
index d43d0d5..ed1fc16 100755
--- a/scripts/redirect.py
+++ b/scripts/redirect.py
@@ -715,7 +715,7 @@
 if code == 1:
 continue
 elif code == 0:
-self.delete_1_broken_redirect(redir_name, delete_reason)
+self.delete_1_broken_redirect(redir_name)
 count += 1
 else:
 self.fix_1_double_redirect(redir_name)

-- 
To view, visit https://gerrit.wikimedia.org/r/107521
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: newchange
Gerrit-Change-Id: Ic3da077470b3358081ed8ffd85ef774d74837d40
Gerrit-PatchSet: 1
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Nullzero 

___
MediaWiki-commits mailing list
MediaWiki-commits@lists.wikimedia.org
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits


[MediaWiki-commits] [Gerrit] Also show a warning on page deletion if a page is transcluded - change (mediawiki/core)

2014-01-17 Thread Nullzero (Code Review)
Nullzero has uploaded a new change for review.

  https://gerrit.wikimedia.org/r/108188


Change subject: Also show a warning on page deletion if a page is transcluded
..

Also show a warning on page deletion if a page is transcluded

[[gerrit:65162]] warns on page deletion if a page which is about to delete
has at least one link to it. This patch improves the previous patch to
warn if at least one page transcludes the deleting page.

Change-Id: If8cb4956297f5d0b040e378f07fcbc43728d687c
---
M includes/Article.php
M languages/messages/MessagesEn.php
M languages/messages/MessagesQqq.php
3 files changed, 4 insertions(+), 3 deletions(-)


  git pull ssh://gerrit.wikimedia.org:29418/mediawiki/core 
refs/changes/88/108188/1

diff --git a/includes/Article.php b/includes/Article.php
index a8cdc48..85a34db 100644
--- a/includes/Article.php
+++ b/includes/Article.php
@@ -1612,7 +1612,8 @@
$outputPage->setPageTitle( wfMessage( 'delete-confirm', 
$this->getTitle()->getPrefixedText() ) );
$outputPage->addBacklinkSubtitle( $this->getTitle() );
$outputPage->setRobotPolicy( 'noindex,nofollow' );
-   if ( $this->getTitle()->getBacklinkCache()->hasLinks( 
'pagelinks' ) ) {
+   $backlinkCache = $this->getTitle()->getBacklinkCache();
+   if ( $backlinkCache->hasLinks( 'pagelinks' ) || 
$backlinkCache->hasLinks( 'templatelinks' ) ) {
$outputPage->wrapWikiMsg( "\n$1\n\n",
'deleting-backlinks-warning' );
}
diff --git a/languages/messages/MessagesEn.php 
b/languages/messages/MessagesEn.php
index d7b300c..11e2597 100644
--- a/languages/messages/MessagesEn.php
+++ b/languages/messages/MessagesEn.php
@@ -3034,7 +3034,7 @@
 'historywarning' => "'''Warning:''' The page you are about to delete 
has a history with approximately $1 {{PLURAL:$1|revision|revisions}}:",
 'confirmdeletetext'  => 'You are about to delete a page along with all of 
its history.
 Please confirm that you intend to do this, that you understand the 
consequences, and that you are doing this in accordance with 
[[{{MediaWiki:Policy-url}}|the policy]].',
-'deleting-backlinks-warning' => "'''Warning:''' Other pages link to the page 
you are about to delete.",
+'deleting-backlinks-warning' => "'''Warning:''' Other pages link to or 
transclude from the page you are about to delete.",
 'actioncomplete' => 'Action complete',
 'actionfailed'   => 'Action failed',
 'deletedtext'=> '"$1" has been deleted.
diff --git a/languages/messages/MessagesQqq.php 
b/languages/messages/MessagesQqq.php
index 64214d2..dc7a9ec 100644
--- a/languages/messages/MessagesQqq.php
+++ b/languages/messages/MessagesQqq.php
@@ -5614,7 +5614,7 @@
 * $1 - the upper limit of number of revisions
 See also:
 * {{msg-mw|Delete-toobig}}',
-'deleting-backlinks-warning' => 'A warning shown when a page that is being 
deleted has links to it.',
+'deleting-backlinks-warning' => 'A warning shown when a page that is being 
deleted has at least one link to it or is transcluded in at least one page.',
 
 # Rollback
 'rollback' => '{{Identical|Rollback}}',

-- 
To view, visit https://gerrit.wikimedia.org/r/108188
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: newchange
Gerrit-Change-Id: If8cb4956297f5d0b040e378f07fcbc43728d687c
Gerrit-PatchSet: 1
Gerrit-Project: mediawiki/core
Gerrit-Branch: master
Gerrit-Owner: Nullzero 

___
MediaWiki-commits mailing list
MediaWiki-commits@lists.wikimedia.org
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits


[MediaWiki-commits] [Gerrit] Update documentation and suppress warning when parsing summary - change (mediawiki/core)

2014-01-18 Thread Nullzero (Code Review)
Nullzero has uploaded a new change for review.

  https://gerrit.wikimedia.org/r/108307


Change subject: Update documentation and suppress warning when parsing summary
..

Update documentation and suppress warning when parsing summary

The documentation states that if contentmodel and title are not given,
but text exists, "wikitext" will be the default model. However, the
actual code will show a warning if do so. This patch fixes the inconsistence
by removing some parts of the documentation which encourages giving
only text as the parameter and corrects the example. The patch
also suppresses the warning that contentmodel must be given when
summary parameter is given.

bug: 60192
Change-Id: I0f41c83763fbb5551aa3ceaff59c1f8fe38310be
---
M includes/api/ApiParse.php
1 file changed, 6 insertions(+), 6 deletions(-)


  git pull ssh://gerrit.wikimedia.org:29418/mediawiki/core 
refs/changes/07/108307/1

diff --git a/includes/api/ApiParse.php b/includes/api/ApiParse.php
index 464fde6..13d234c 100644
--- a/includes/api/ApiParse.php
+++ b/includes/api/ApiParse.php
@@ -186,8 +186,9 @@
}
 
$popts = $this->makeParserOptions( $pageObj, $params );
+   $textProvided = !is_null( $text );
 
-   if ( is_null( $text ) ) {
+   if ( !$textProvided ) {
if ( $titleProvided && ( $prop || 
$params['generatexml'] ) ) {
$this->setWarning(
"'title' used without 'text', 
and parsed page properties were requested " .
@@ -200,7 +201,7 @@
 
// If we are parsing text, do not use the content model 
of the default
// API title, but default to wikitext to keep BC.
-   if ( !$titleProvided && is_null( $model ) ) {
+   if ( $textProvided && !$titleProvided && is_null( 
$model ) ) {
$model = CONTENT_MODEL_WIKITEXT;
$this->setWarning( "No 'title' or 
'contentmodel' was given, assuming $model." );
}
@@ -710,14 +711,13 @@
 
public function getParamDescription() {
$p = $this->getModulePrefix();
-   $wikitext = CONTENT_MODEL_WIKITEXT;
 
return array(
'text' => "Text to parse. Use {$p}title or 
{$p}contentmodel to control the content model",
'summary' => 'Summary to parse',
'redirects' => "If the {$p}page or the {$p}pageid 
parameter is set to a redirect, resolve it",
'title' => "Title of page the text belongs to. " .
-   "If omitted, \"API\" is used as the title with 
content model $wikitext",
+   "If omitted, \"API\" is used as the title",
'page' => "Parse the content of this page. Cannot be 
used together with {$p}text and {$p}title",
'pageid' => "Parse the content of this page. Overrides 
{$p}page",
'oldid' => "Parse the content of this revision. 
Overrides {$p}page and {$p}pageid",
@@ -768,7 +768,7 @@
),
'contentmodel' => array(
"Content model of the input text. Default is 
the model of the " .
-   "specified ${p}title, or $wikitext if ${p}title 
is not specified",
+   "specified ${p}title if ${p}title is specified",
"Only valid when used with {$p}text",
),
);
@@ -814,7 +814,7 @@
public function getExamples() {
return array(
'api.php?action=parse&page=Project:Sandbox' => 'Parse a 
page',
-   'api.php?action=parse&text={{Project:Sandbox}}' => 
'Parse wikitext',
+   
'api.php?action=parse&text={{Project:Sandbox}}&contentmodel=wikitext' => 'Parse 
wikitext',
'api.php?action=parse&text={{PAGENAME}}&title=Test'
=> 'Parse wikitext, specifying the page title',
'api.php?action=parse&summary=Some+[[link]]&prop=' => 
'Parse a summary',

-- 
To view, visit https://gerrit.wikimedia.org/r/108307
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: newchange
Gerrit-Change-Id: I0f41c83763fbb5551aa3ceaff59c1f8fe38310be
Gerrit-PatchSet: 1
Gerrit-Project: mediawiki/core
Gerrit-Branch: master
Gerrit-Owner: Nullzero 

___
MediaWiki-commits mailing list
MediaWiki-commits@lists.wikimedia.org
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits


[MediaWiki-commits] [Gerrit] Suppress warning when parsing text - change (pywikibot/core)

2014-01-19 Thread Nullzero (Code Review)
Nullzero has uploaded a new change for review.

  https://gerrit.wikimedia.org/r/108341


Change subject: Suppress warning when parsing text
..

Suppress warning when parsing text

From bug:60192, parsing text should always include contentmodel if
title is not specified. Otherwise, there will be a warning from API
(confirmed in http://sourceforge.net/p/pywikipediabot/bugs/1641/)

Change-Id: I2b28ff54fbc750a0a91d3a1ad9f299fb64bcf620
---
M pywikibot/site.py
1 file changed, 2 insertions(+), 1 deletion(-)


  git pull ssh://gerrit.wikimedia.org:29418/pywikibot/core 
refs/changes/41/108341/1

diff --git a/pywikibot/site.py b/pywikibot/site.py
index a232365..1000e73 100644
--- a/pywikibot/site.py
+++ b/pywikibot/site.py
@@ -1045,7 +1045,8 @@
 """
 r = api.Request(site=self,
 action="parse",
-text="{{CURRENTTIMESTAMP}}")
+text="{{CURRENTTIMESTAMP}}",
+contentmodel="wikitext")
 result = r.submit()
 return re.search('\d+', result['parse']['text']['*']).group()
 

-- 
To view, visit https://gerrit.wikimedia.org/r/108341
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: newchange
Gerrit-Change-Id: I2b28ff54fbc750a0a91d3a1ad9f299fb64bcf620
Gerrit-PatchSet: 1
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Nullzero 

___
MediaWiki-commits mailing list
MediaWiki-commits@lists.wikimedia.org
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits


[MediaWiki-commits] [Gerrit] Link to corresponding message in translatewiki directly - change (mediawiki/core)

2014-06-24 Thread Nullzero (Code Review)
Nullzero has uploaded a new change for review.

  https://gerrit.wikimedia.org/r/141728

Change subject: Link to corresponding message in translatewiki directly
..

Link to corresponding message in translatewiki directly

fa5576bee53 added an external link to translatewiki to every message
in Special:AllMessages. While this change is a very good idea, the result
does not work as was intended. This patch therefore fixes the problem.

To be more clear, in the former commit, it was stated that the external links
will link to translatewiki.net at page Special:SearchTranslations with three
queries: key and text search. It was intended to use
Special:SearchTranslations because:

the solr search is smart enough to present the most relevant results
first and the translation interface is directly available in place.
On the bright side, similar messages popping up from other projects or
areas of the code will provide suggestions and help find other
occurrences of translations which can similarly be improved.
-- Federico Leva 
   Thu Nov 7 00:08:02 2013 +0100

However, for non-English language (Thai, Lao, for example), very frequently
the solr search is NOT smart enough to look up the correct message.
Many times the correct message does not show up in the search page at all.
Linking to the corresponding message directly therefore would be
more effective.

Change-Id: Ic52dc0e157226a0a1f8cd2253afebed572fe0d47
---
M includes/specials/SpecialAllMessages.php
1 file changed, 2 insertions(+), 6 deletions(-)


  git pull ssh://gerrit.wikimedia.org:29418/mediawiki/core 
refs/changes/28/141728/1

diff --git a/includes/specials/SpecialAllMessages.php 
b/includes/specials/SpecialAllMessages.php
index d44b94e..19fcee5 100644
--- a/includes/specials/SpecialAllMessages.php
+++ b/includes/specials/SpecialAllMessages.php
@@ -367,12 +367,8 @@
$talk = Title::makeTitle( NS_MEDIAWIKI_TALK, 
$value . $this->suffix );
$translation = Linker::makeExternalLink(
'https://translatewiki.net/w/i.php?' . 
wfArrayToCgi( array(
-   'title' => 
'Special:SearchTranslations',
-   'group' => 'mediawiki',
-   'grouppath' => 'mediawiki',
-   'query' => 'language:' . 
$this->getLanguage()->getCode() . '^25 ' .
-   'messageid:"MediaWiki:' 
. $value . '"^10 "' .
-   $this->msg( $value 
)->inLanguage( 'en' )->plain() . '"'
+   'title' => 'MediaWiki:' . 
$value . '/' . $this->getLanguage()->getCode(),
+   'action' => 'edit'
) ),
$this->msg( 
'allmessages-filter-translate' )->text()
);

-- 
To view, visit https://gerrit.wikimedia.org/r/141728
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: newchange
Gerrit-Change-Id: Ic52dc0e157226a0a1f8cd2253afebed572fe0d47
Gerrit-PatchSet: 1
Gerrit-Project: mediawiki/core
Gerrit-Branch: master
Gerrit-Owner: Nullzero 

___
MediaWiki-commits mailing list
MediaWiki-commits@lists.wikimedia.org
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits


[MediaWiki-commits] [Gerrit] Code cleaning of redirect.py - change (pywikibot/core)

2014-06-14 Thread Nullzero (Code Review)
Nullzero has uploaded a new change for review.

  https://gerrit.wikimedia.org/r/139598

Change subject: Code cleaning of redirect.py
..

Code cleaning of redirect.py

Change-Id: I764cfbcc55c0cc2b585cc55ccf3a5874572b17cd
---
M scripts/redirect.py
1 file changed, 1 insertion(+), 6 deletions(-)


  git pull ssh://gerrit.wikimedia.org:29418/pywikibot/core 
refs/changes/98/139598/1

diff --git a/scripts/redirect.py b/scripts/redirect.py
index 80de7bb..f76897e 100755
--- a/scripts/redirect.py
+++ b/scripts/redirect.py
@@ -708,8 +708,6 @@
 def fix_double_or_delete_broken_redirects(self):
 # TODO: part of this should be moved to generator, the rest merged into
 # self.run()
-# get reason for deletion text
-delete_reason = i18n.twtranslate(self.site, 'redirect-remove-broken')
 count = 0
 for (redir_name, code, target, final)\
 in self.generator.get_redirects_via_api(maxlen=2):
@@ -821,7 +819,4 @@
 bot.run()
 
 if __name__ == '__main__':
-try:
-main()
-finally:
-pywikibot.stopme()
+main()

-- 
To view, visit https://gerrit.wikimedia.org/r/139598
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: newchange
Gerrit-Change-Id: I764cfbcc55c0cc2b585cc55ccf3a5874572b17cd
Gerrit-PatchSet: 1
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Nullzero 

___
MediaWiki-commits mailing list
MediaWiki-commits@lists.wikimedia.org
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits


[MediaWiki-commits] [Gerrit] (noreferences.py) add a config for Thai Wikipedia - change (pywikibot/core)

2014-06-14 Thread Nullzero (Code Review)
Nullzero has uploaded a new change for review.

  https://gerrit.wikimedia.org/r/139656

Change subject: (noreferences.py) add a config for Thai Wikipedia
..

(noreferences.py) add a config for Thai Wikipedia

Change-Id: If4f9d3613eaa89d33034bf6f6e40dbe80b22b2ae
---
M scripts/noreferences.py
1 file changed, 13 insertions(+), 0 deletions(-)


  git pull ssh://gerrit.wikimedia.org:29418/pywikibot/core 
refs/changes/56/139656/1

diff --git a/scripts/noreferences.py b/scripts/noreferences.py
index 871ed13..3e93011 100755
--- a/scripts/noreferences.py
+++ b/scripts/noreferences.py
@@ -193,6 +193,12 @@
 u'Przipisy',
 u'Připisy',
 ],
+'th': [
+u'อ่านเพิ่มเติม',
+u'แหล่งข้อมูลอื่น',
+u'ดูเพิ่ม',
+u'หมายเหตุ'
+],
 'zh': [
 u'外部链接',
 u'外部連结',
@@ -330,6 +336,11 @@
 u'Przipisy',
 u'Připisy',
 ],
+'th': [
+u'อ้างอิง',
+u'เชิงอรรถ',
+u'หมายเหตุ',
+],
 'zh': [
 u'參考資料',
 u'参考资料',
@@ -379,6 +390,7 @@
u'Примечания', u'Список примечаний',
u'Сноска', u'Сноски'],
 'szl': [u'Przipisy', u'Připisy'],
+'en': [u'รายการอ้างอิง'],
 'zh': [u'Reflist', u'RefFoot', u'NoteFoot'],
 },
 }
@@ -399,6 +411,7 @@
 'pl': u'{{Przypisy}}',
 'ru': u'{{примечания}}',
 'szl': u'{{Przipisy}}',
+'th': u'{{รายการอ้างอิง}}',
 'zh': u'{{reflist}}',
 },
 }

-- 
To view, visit https://gerrit.wikimedia.org/r/139656
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: newchange
Gerrit-Change-Id: If4f9d3613eaa89d33034bf6f6e40dbe80b22b2ae
Gerrit-PatchSet: 1
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Nullzero 

___
MediaWiki-commits mailing list
MediaWiki-commits@lists.wikimedia.org
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits


[MediaWiki-commits] [Gerrit] Support protecting action=create/upload - change (pywikibot/core)

2014-06-16 Thread Nullzero (Code Review)
Nullzero has uploaded a new change for review.

  https://gerrit.wikimedia.org/r/139792

Change subject: Support protecting action=create/upload
..

Support protecting action=create/upload

This patch makes it possible to protect creating a page or uploading a file.
Note that it is a breaking change since parameter "create" and "upload" are
inserted between the old parameters. However, for Page.protect(), it is unlikel
anyone will be affected negatively by this patch because most people would call
this function by specifying keyword argument. For APISite.protect(), no one wou
call it directly. This change therefore should not be problematic.

Besides this, I correct/elaborate docstring. I also change my name in CREDITS
to my preferable name.

Change-Id: I595228ea9a61f7e55dc14f8c3682494c8938cb1e
---
M CREDITS
M pywikibot/page.py
M pywikibot/site.py
3 files changed, 36 insertions(+), 14 deletions(-)


  git pull ssh://gerrit.wikimedia.org:29418/pywikibot/core 
refs/changes/92/139792/1

diff --git a/CREDITS b/CREDITS
index d99b3fe..a87d3e5 100644
--- a/CREDITS
+++ b/CREDITS
@@ -53,7 +53,6 @@
 Mpaa
 Nicolas Dumazet
 notconfusing
-Nullzer0
 Philip Tzou
 Platonides
 Purodha B Blissenbach
@@ -67,6 +66,7 @@
 Shinjiman
 Shi Zhao
 Siebrand Mazeland
+Sorawee Porncharoenwase
 Steve Sanbeg
 Sumana Harihareswara
 Thomas R. Koll
diff --git a/pywikibot/page.py b/pywikibot/page.py
index b19c09a..9267d7d 100644
--- a/pywikibot/page.py
+++ b/pywikibot/page.py
@@ -1457,21 +1457,27 @@
 return self.site.undelete(self, comment)
 
 @deprecate_arg("throttle", None)
-def protect(self, edit='sysop', move='sysop', unprotect=False,
-reason=None, prompt=True, expiry=None):
+def protect(self, edit='sysop', move='sysop', create=None, upload=None,
+unprotect=False, reason=None, prompt=True, expiry=None):
 """(Un)protect a wiki page. Requires administrator status.
 
 Valid protection levels (in MediaWiki 1.12) are '' (equivalent to
-'none'), 'autoconfirmed', and 'sysop'.
+'none'), 'autoconfirmed', and 'sysop'. If None is given, however,
+that protection will be skipped.
 
 @param edit: Level of edit protection
 @param move: Level of move protection
+@param create: Level of create protection
+@param upload: Level of upload protection
 @param unprotect: If true, unprotect the page (equivalent to setting
 all protection levels to '')
 @param reason: Edit summary.
 @param prompt: If true, ask user for confirmation.
-@param expiry: When the block should expire
-
+@param expiry: When the block should expire. This expiry will be 
applied
+   to all protections. Possible type of value is
+   pywikibot.Timestamp, string in GNU timestamp format
+   (including ISO 8601). If None, "infinite", "indefinite",
+   "never", or empty string is given, there is no expiry.
 """
 if reason is None:
 if unprotect:
@@ -1482,7 +1488,7 @@
  % (un, self.title(asLink=True)))
 reason = pywikibot.input(u'Please enter a reason for the action:')
 if unprotect:
-edit = move = ""
+edit = move = create = upload = ""
 answer = 'y'
 if prompt and not hasattr(self.site, '_noProtectPrompt'):
 answer = pywikibot.inputChoice(
@@ -1495,7 +1501,7 @@
 answer = 'y'
 self.site._noProtectPrompt = True
 if answer in ['y', 'Y']:
-return self.site.protect(self, edit, move, reason, expiry)
+return self.site.protect(self, edit, move, create, upload, reason, 
exp
 
 def change_category(self, oldCat, newCat, comment=None, sortKey=None,
 inPlace=True):
diff --git a/pywikibot/site.py b/pywikibot/site.py
index 7e621a3..2fc07bb 100644
--- a/pywikibot/site.py
+++ b/pywikibot/site.py
@@ -3078,26 +3078,42 @@
 }
 
 @must_be(group='sysop')
-def protect(self, page, edit, move, summary, expiry=None):
+def protect(self, page, edit, move, create, upload, summary, expiry=None):
 """(Un)protect a wiki page. Requires administrator status.
 
 Valid protection levels (in MediaWiki 1.12) are '' (equivalent to
-'none'), 'autoconfirmed', and 'sysop'.
+'none'), 'autoconfirmed', and 'sysop'. If None is given, however,
+that protection will be skipped.
 
 @param edit: Level of edit protection
 @param move: Level of move protection
+@param create: Level of create protection
+@param upload: Level of upload protection
 @param unprotect: If true, unprotect the page (equivalent to setting
 all protection levels to '')
 @param reason: Edit summary.
-@param prompt: If

[MediaWiki-commits] [Gerrit] Speeding up touch.py by setting async=True - change (pywikibot/core)

2014-06-24 Thread Nullzero (Code Review)
Nullzero has uploaded a new change for review.

  https://gerrit.wikimedia.org/r/141682

Change subject: Speeding up touch.py by setting async=True
..

Speeding up touch.py by setting async=True

Since touch.py does not involve user interaction, it can use async=True
to speed up the running time. async=True can be used safely because this
script does not alter content of any page.

Change-Id: I35ed1615a907828bb035219b8b992d1c649a601f
---
M scripts/touch.py
1 file changed, 3 insertions(+), 16 deletions(-)


  git pull ssh://gerrit.wikimedia.org:29418/pywikibot/core 
refs/changes/82/141682/1

diff --git a/scripts/touch.py b/scripts/touch.py
index 44bb153..95e0f5d 100755
--- a/scripts/touch.py
+++ b/scripts/touch.py
@@ -49,26 +49,13 @@
 pywikibot.output(u'Page %s%s purged'
  % (page.title(asLink=True),
 "" if page.purge() else " not"))
-continue
-try:
+else:
 # get the page, and save it using the unmodified text.
 # whether or not getting a redirect throws an exception
 # depends on the variable self.touch_redirects.
 page.get(get_redirect=self.getOption('redir'))
-page.save("Pywikibot touch script")
-except pywikibot.NoPage:
-pywikibot.error(u"Page %s does not exist."
-% page.title(asLink=True))
-except pywikibot.IsRedirectPage:
-pywikibot.warning(u"Page %s is a redirect; skipping."
-  % page.title(asLink=True))
-except pywikibot.LockedPage:
-pywikibot.error(u"Page %s is locked."
-% page.title(asLink=True))
-except pywikibot.PageNotSaved:
-pywikibot.error(u"Page %s not saved."
-% page.title(asLink=True))
-
+# Save the page in the background. No need to catch exceptions.
+page.save("Pywikibot touch script", async=True)
 
 def main(*args):
 gen = None

-- 
To view, visit https://gerrit.wikimedia.org/r/141682
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: newchange
Gerrit-Change-Id: I35ed1615a907828bb035219b8b992d1c649a601f
Gerrit-PatchSet: 1
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Nullzero 

___
MediaWiki-commits mailing list
MediaWiki-commits@lists.wikimedia.org
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits


[MediaWiki-commits] [Gerrit] Add an alternative way to implement page.touch() - change (pywikibot/core)

2014-10-25 Thread Nullzero (Code Review)
Nullzero has uploaded a new change for review.

  https://gerrit.wikimedia.org/r/168770

Change subject: Add an alternative way to implement page.touch()
..

Add an alternative way to implement page.touch()

With new parameter `append` in editpage, we can touch a page without
having to preload anything at all. The data we send would be only
an empty string which would make touching faster significantly.

Because we don't check anything at all (just send a request to the API),
we have to use nocreate to prevent page creation. If page doesn't exist,
with nocreate=True, the exception will be pywikibot.data.api.APIError,
not pywikibot.NoPage. In next patch it would be a good idea to make
exception in this case become pywikibot.NoPage as well. This patch
will not fix this issue, though.

Also, because we don't check anything at all, we can't detect a redirect.
That means, the program will consider a redirect just a normal page
and doesn't resolve redirect automatically.

Change-Id: I714fb658a47ef56f1d4d1c78b367c67fea429e0f
---
M pywikibot/page.py
M pywikibot/site.py
M scripts/touch.py
3 files changed, 19 insertions(+), 15 deletions(-)


  git pull ssh://gerrit.wikimedia.org:29418/pywikibot/core 
refs/changes/70/168770/1

diff --git a/pywikibot/page.py b/pywikibot/page.py
index 2c3db36..1e21226 100644
--- a/pywikibot/page.py
+++ b/pywikibot/page.py
@@ -1090,6 +1090,12 @@
 """
 return self.site.purgepages([self], **kwargs)
 
+def touch(self):
+"""Make a touch edit for this page."""
+self.text = ""
+return self.site.editpage(self, summary="Pywikibot touch edit",
+  nocreate=True, append=True)
+
 def linkedPages(self, namespaces=None, step=None, total=None,
 content=False):
 """Iterate Pages that this Page links to.
diff --git a/pywikibot/site.py b/pywikibot/site.py
index dffd696..c519561 100644
--- a/pywikibot/site.py
+++ b/pywikibot/site.py
@@ -3693,7 +3693,7 @@
 @must_be(group='user')
 def editpage(self, page, summary, minor=True, notminor=False,
  bot=True, recreate=True, createonly=False, nocreate=False,
- watch=None):
+ watch=None, append=False):
 """Submit an edited Page object to be saved to the wiki.
 
 @param page: The Page to be saved; its .text property will be used
@@ -3714,6 +3714,7 @@
 * preferences: use the preference settings (Default)
 * nochange: don't change the watchlist
 @param botflag: if True, mark edit with bot flag
+@param append: if True, append text in .text to the page instead
 @return: True if edit succeeded, False if it failed
 
 """
@@ -3738,7 +3739,11 @@
 raise EditConflict(page)
 params = dict(action="edit",
   title=page.title(withSection=False),
-  text=text, token=token, summary=summary)
+  token=token, summary=summary)
+if append:
+params["appendtext"] = text
+else:
+params["text"] = text
 if bot:
 params["bot"] = ""
 if lastrev is not None:
diff --git a/scripts/touch.py b/scripts/touch.py
index 8048a57..2edcedf 100755
--- a/scripts/touch.py
+++ b/scripts/touch.py
@@ -26,6 +26,7 @@
 
 import pywikibot
 from pywikibot import pagegenerators
+from pywikibot.data.api import APIError
 
 docuReplacements = {'¶ms;': pagegenerators.parameterHelp}
 
@@ -51,22 +52,15 @@
 "" if page.purge() else " not"))
 continue
 try:
-# get the page, and save it using the unmodified text.
-# whether or not getting a redirect throws an exception
-# depends on the variable self.touch_redirects.
-page.get(get_redirect=self.getOption('redir'))
-page.save("Pywikibot touch script")
-except pywikibot.NoPage:
-pywikibot.error(u"Page %s does not exist."
-% page.title(asLink=True))
-except pywikibot.IsRedirectPage:
-pywikibot.warning(u"Page %s is a redirect; skipping."
-  % page.title(asLink=True))
+page.touch()
 except pywikibot.LockedPage:
 pywikibot.error(u"Page %s is locked."
 % page.title(asLink=True))
 except pywikibot.PageNotSaved:
 pywikibot.error(u"Page %s not saved."
+% page.title(asLink=True))
+except APIError:
+pywikibot.error(u"Page %s does not exist."
 % page.title(asLink=True))
 
 
@@ -94,8 +88,7 @@
 
 gen = genFactory.getCombinedGenerator()
 if gen:
-preloadingGen = pagegenerators.Prelo

[MediaWiki-commits] [Gerrit] Add NoCreateError and fix a bug about issubclass - change (pywikibot/core)

2014-10-25 Thread Nullzero (Code Review)
Nullzero has uploaded a new change for review.

  https://gerrit.wikimedia.org/r/168816

Change subject: Add NoCreateError and fix a bug about issubclass
..

Add NoCreateError and fix a bug about issubclass

With nocreate=True, if page doesn't exist, API will return
missingtitle which is not recognized by PWB. This patch adds
NoCreateError to match with this missingtitle in this case.

This patch also fixes a bug when issubclass is used but the first
parameter is not a class, leading to an error
"TypeError: issubclass() arg 1 must be a class"

Change-Id: I11f80783c9febce51538e868a0b1edb42cce4ec3
---
M pywikibot/__init__.py
M pywikibot/exceptions.py
M pywikibot/site.py
3 files changed, 15 insertions(+), 5 deletions(-)


  git pull ssh://gerrit.wikimedia.org:29418/pywikibot/core 
refs/changes/16/168816/1

diff --git a/pywikibot/__init__.py b/pywikibot/__init__.py
index ad0c475..14327d2 100644
--- a/pywikibot/__init__.py
+++ b/pywikibot/__init__.py
@@ -40,7 +40,7 @@
 NoUsername, UserBlocked,
 PageRelatedError, IsRedirectPage, IsNotRedirectPage,
 PageSaveRelatedError, PageNotSaved, OtherPageSaveError,
-LockedPage, CascadeLockedPage, LockedNoPage,
+LockedPage, CascadeLockedPage, LockedNoPage, NoCreateError,
 EditConflict, PageDeletedConflict, PageCreatedConflict,
 ServerError, FatalServerError, Server504Error,
 CaptchaError, SpamfilterError, CircularRedirect,
@@ -76,7 +76,7 @@
'NoUsername', 'UserBlocked',
'PageRelatedError', 'IsRedirectPage', 'IsNotRedirectPage',
'PageSaveRelatedError', 'PageNotSaved', 'OtherPageSaveError',
-   'LockedPage', 'CascadeLockedPage', 'LockedNoPage',
+   'LockedPage', 'CascadeLockedPage', 'LockedNoPage', 'NoCreateError',
'EditConflict', 'PageDeletedConflict', 'PageCreatedConflict',
'UploadWarning',
'ServerError', 'FatalServerError', 'Server504Error',
diff --git a/pywikibot/exceptions.py b/pywikibot/exceptions.py
index ad0c566..d735038 100644
--- a/pywikibot/exceptions.py
+++ b/pywikibot/exceptions.py
@@ -35,6 +35,7 @@
   - PageDeletedConflict: Page was deleted since being retrieved
   - PageCreatedConflict: Page was created by another user
   - ArticleExistsConflict: Page article already exists
+  - NoCreateError: parameter nocreate not allow page creation
 
 ServerError: a problem with the server.
   - FatalServerError: A fatal/non-recoverable server error
@@ -259,6 +260,13 @@
 
 PageNotSaved = PageSaveRelatedError
 
+class NoCreateError(PageSaveRelatedError):
+
+"""Parameter nocreate doesn't allow page creation."""
+
+message = u"Page %s could not be created due to parameter nocreate"
+
+pass
 
 class EditConflict(PageSaveRelatedError):
 
diff --git a/pywikibot/site.py b/pywikibot/site.py
index dffd696..17611ee 100644
--- a/pywikibot/site.py
+++ b/pywikibot/site.py
@@ -50,6 +50,7 @@
 SiteDefinitionError,
 NoUsername,
 SpamfilterError,
+NoCreateError,
 UserBlocked,
 )
 
@@ -3682,6 +3683,7 @@
 "noedit-anon": """Bot is not logged in, and anon users are not 
authorized to edit on %(site)s wiki""",
 "noedit": "User %(user)s not authorized to edit pages on %(site)s 
wiki",
 
+"missingtitle": NoCreateError,
 "editconflict": EditConflict,
 "articleexists": PageCreatedConflict,
 "pagedeleted": PageDeletedConflict,
@@ -3775,9 +3777,7 @@
 % err.code,
 _logger)
 if err.code in self._ep_errors:
-if issubclass(self._ep_errors[err.code], 
PageSaveRelatedError):
-raise self._ep_errors[err.code](page)
-else:
+if isinstance(self._ep_errors[err.code], basestring):
 errdata = {
 'site': self,
 'title': page.title(withSection=False),
@@ -3785,6 +3785,8 @@
 'info': err.info
 }
 raise Error(self._ep_errors[err.code] % errdata)
+else:
+raise self._ep_errors[err.code](page)
 pywikibot.debug(
 u"editpage: Unexpected error code '%s' received."
 % err.code,

-- 
To view, visit https://gerrit.wikimedia.org/r/168816
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: newchange
Gerrit-Change-Id: I11f80783c9febce51538e868a0b1edb42cce4ec3
Gerrit-PatchSet: 1
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Nullzero 

___
MediaWiki-commits mailing list
MediaWiki-commits@lists.wikimedia.org
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits


[MediaWiki-commits] [Gerrit] Remove wrong comment and unused code - change (pywikibot/core)

2014-10-27 Thread Nullzero (Code Review)
Nullzero has uploaded a new change for review.

  https://gerrit.wikimedia.org/r/169311

Change subject: Remove wrong comment and unused code
..

Remove wrong comment and unused code

Because we switch to the tokens property, the comment that latestRevision
will be updated is no longer true. We also can't check edit conflict from
this. This patch therefore removes the comment and the code

Change-Id: I288c9badb7824dc2bc8db300e7fa6c322b338640
---
M pywikibot/site.py
1 file changed, 2 insertions(+), 10 deletions(-)


  git pull ssh://gerrit.wikimedia.org:29418/pywikibot/core 
refs/changes/11/169311/1

diff --git a/pywikibot/site.py b/pywikibot/site.py
index 4efece2..9cadefe 100644
--- a/pywikibot/site.py
+++ b/pywikibot/site.py
@@ -3728,24 +3728,16 @@
 if not recreate:
 raise
 token = self.tokens['edit']
-# getting token also updates the 'lastrevid' value, which allows us to
-# detect if page has been changed since last time text was retrieved.
-
-# note that the server can still return an 'editconflict' error
-# if the page is updated after the token is retrieved but
-# before the page is saved.
 self.lock_page(page)
-if lastrev is not None and page.latestRevision() != lastrev:
-raise EditConflict(page)
 params = dict(action="edit",
   title=page.title(withSection=False),
   text=text, token=token, summary=summary)
 if bot:
-params["bot"] = ""
+params['bot'] = ""
 if lastrev is not None:
 if lastrev not in page._revisions:
 self.loadrevisions(page)
-params["basetimestamp"] = page._revisions[lastrev].timestamp
+params['basetimestamp'] = page._revisions[lastrev].timestamp
 if minor:
 params['minor'] = ""
 elif notminor:

-- 
To view, visit https://gerrit.wikimedia.org/r/169311
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: newchange
Gerrit-Change-Id: I288c9badb7824dc2bc8db300e7fa6c322b338640
Gerrit-PatchSet: 1
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Nullzero 

___
MediaWiki-commits mailing list
MediaWiki-commits@lists.wikimedia.org
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits


[MediaWiki-commits] [Gerrit] Log test start and end, and result - change (pywikibot/core)

2014-10-28 Thread Nullzero (Code Review)
Nullzero has submitted this change and it was merged.

Change subject: Log test start and end, and result
..


Log test start and end, and result

Add debug log messages for the start and end of each unit test.

Change-Id: I701dfa1fbdb21982664c537346986da5f57f6ccd
---
M tests/aspects.py
1 file changed, 64 insertions(+), 3 deletions(-)

Approvals:
  John Vandenberg: Looks good to me, but someone else must approve
  Nullzero: Looks good to me, approved



diff --git a/tests/aspects.py b/tests/aspects.py
index 3089fc3..2f58950 100644
--- a/tests/aspects.py
+++ b/tests/aspects.py
@@ -32,10 +32,11 @@
 import time
 import sys
 import os
+import inspect
 
 import pywikibot
 
-from pywikibot import config, Site
+from pywikibot import config, log, Site
 from pywikibot.site import BaseSite
 from pywikibot.family import WikimediaFamily
 
@@ -63,6 +64,66 @@
 assertRegexpMatches is deprecated in Python 3.
 """
 return self.assertRegexpMatches(*args, **kwargs)
+
+
+class TestLoggingMixin(TestCaseBase):
+
+"""Logging for test cases."""
+
+@classmethod
+def setUpClass(cls):
+"""Set up test class."""
+cls._log_prefix = inspect.getfile(cls) + ':' + cls.__name__
+
+def setUp(self):
+"""Set up each unit test."""
+super(TestLoggingMixin, self).setUp()
+
+if hasattr(self, '_outcomeForDoCleanups'):
+# Python 3 unittest & nose
+outcome = self._outcomeForDoCleanups
+elif hasattr(self, '_outcome'):
+# Python 3.4 nose
+outcome = self._outcome
+elif hasattr(self, '_resultForDoCleanups'):
+# Python 2 unittest & nose
+outcome = self._resultForDoCleanups
+else:
+return
+
+self._previous_errors = len(outcome.errors)
+# nose 3.4 doesn't has failures
+if hasattr(outcome, 'failures'):
+self._previous_failures = len(outcome.failures)
+
+log('START ' + self._log_prefix + '.' + self._testMethodName)
+
+def tearDown(self):
+"""Tear down test."""
+super(TestLoggingMixin, self).tearDown()
+
+if hasattr(self, '_outcomeForDoCleanups'):
+# Python 3 unittest & nose
+outcome = self._outcomeForDoCleanups
+elif hasattr(self, '_outcome'):
+# Python 3.4 nose
+outcome = self._outcome
+elif hasattr(self, '_resultForDoCleanups'):
+# Python 2 unittest & nose
+outcome = self._resultForDoCleanups
+else:
+return
+
+if len(outcome.errors) > self._previous_errors:
+status = ' NOT OK: ERROR'
+# nose 3.4 doesn't has failures
+elif (hasattr(outcome, 'failures') and
+len(outcome.failures) > self._previous_failures):
+status = ' NOT OK: FAILURE'
+else:
+status = ' OK'
+
+log('END ' + self._log_prefix + '.' + self._testMethodName + status)
 
 
 class TestTimerMixin(TestCaseBase):
@@ -402,9 +463,9 @@
 return super(MetaTestCaseClass, cls).__new__(cls, name, bases, dct)
 
 
-class TestCase(TestTimerMixin, TestCaseBase):
+class TestCase(TestTimerMixin, TestLoggingMixin, TestCaseBase):
 
-"""Run tests on multiple sites."""
+"""Run tests on pre-defined sites."""
 
 __metaclass__ = MetaTestCaseClass
 

-- 
To view, visit https://gerrit.wikimedia.org/r/146042
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: merged
Gerrit-Change-Id: I701dfa1fbdb21982664c537346986da5f57f6ccd
Gerrit-PatchSet: 5
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: John Vandenberg 
Gerrit-Reviewer: John Vandenberg 
Gerrit-Reviewer: Ladsgroup 
Gerrit-Reviewer: Legoktm 
Gerrit-Reviewer: Merlijn van Deen 
Gerrit-Reviewer: Nullzero 
Gerrit-Reviewer: XZise 
Gerrit-Reviewer: jenkins-bot <>

___
MediaWiki-commits mailing list
MediaWiki-commits@lists.wikimedia.org
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits


[MediaWiki-commits] [Gerrit] Add a parameter "transclusion" to Page.categories() - change (pywikibot/core)

2014-07-23 Thread Nullzero (Code Review)
Nullzero has uploaded a new change for review.

  https://gerrit.wikimedia.org/r/148619

Change subject: Add a parameter "transclusion" to Page.categories()
..

Add a parameter "transclusion" to Page.categories()

This patch adds a parameter "transclusion", which, if True,
will retrieve categories from API, which include transcluded categories.
Otherwise, it will retrieve categories from wikitext directly.

Note that in the second case, we retrieve categories from API and then filter
trancluded categories out. This is to make parameter "content" works properly.

Change-Id: I9cf1a3968e0393b19f8461ab355213fd1877dc22
---
M pywikibot/page.py
1 file changed, 14 insertions(+), 5 deletions(-)


  git pull ssh://gerrit.wikimedia.org:29418/pywikibot/core 
refs/changes/19/148619/1

diff --git a/pywikibot/page.py b/pywikibot/page.py
index c6473bc..0288e00 100644
--- a/pywikibot/page.py
+++ b/pywikibot/page.py
@@ -39,6 +39,7 @@
 import sys
 import unicodedata
 import collections
+import itertools
 
 import urllib
 
@@ -1267,8 +1268,9 @@
 
 @deprecate_arg("nofollow_redirects", None)
 @deprecate_arg("get_redirect", None)
-def categories(self, withSortKey=False, step=None, total=None,
-   content=False):
+@deprecate_arg("withSortKey", None)
+def categories(self, step=None, total=None, content=False,
+   transclusion=True):
 """Iterate categories that the article is in.
 
 @param withSortKey: if True, include the sort key in each Category.
@@ -1276,11 +1278,18 @@
 @param total: iterate no more than this number of pages in total
 @param content: if True, retrieve the content of the current version
 of each category description page (default False)
+@param transclusion: if True, include categories from transclusion
 @return: a generator that yields Category objects.
 
 """
-return self.site.pagecategories(self, withSortKey=withSortKey,
-step=step, total=total, 
content=content)
+wTransclusion = self.site.pagecategories(self, step=step,
+ total=total, content=content)
+if transclusion:
+return withTransclusion
+else:
+woTransclusion = pywikibot.textlib.getCategoryLinks(self.text)
+return itertools.ifilter(lambda cat: cat in woTransclusion,
+ wTransclusion)
 
 def extlinks(self, step=None, total=None):
 """Iterate all external URLs (not interwiki links) from this page.
@@ -1630,7 +1639,7 @@
 # get list of Category objects the article is in and remove possible
 # duplicates
 cats = []
-for cat in pywikibot.textlib.getCategoryLinks(self.text):
+for cat in self.categories(transclusion=False):
 if cat not in cats:
 cats.append(cat)
 

-- 
To view, visit https://gerrit.wikimedia.org/r/148619
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: newchange
Gerrit-Change-Id: I9cf1a3968e0393b19f8461ab355213fd1877dc22
Gerrit-PatchSet: 1
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Nullzero 

___
MediaWiki-commits mailing list
MediaWiki-commits@lists.wikimedia.org
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits


[MediaWiki-commits] [Gerrit] Fix docstrings and PEP257 - change (pywikibot/core)

2014-08-09 Thread Nullzero (Code Review)
Nullzero has uploaded a new change for review.

  https://gerrit.wikimedia.org/r/153224

Change subject: Fix docstrings and PEP257
..

Fix docstrings and PEP257

Change-Id: I3406bee8df5c244703f744b9dd83b953af983517
---
M pywikibot/data/api.py
1 file changed, 42 insertions(+), 20 deletions(-)


  git pull ssh://gerrit.wikimedia.org:29418/pywikibot/core 
refs/changes/24/153224/1

diff --git a/pywikibot/data/api.py b/pywikibot/data/api.py
index 2bdb78a..efe88b3 100644
--- a/pywikibot/data/api.py
+++ b/pywikibot/data/api.py
@@ -47,7 +47,9 @@
 
 
 class APIError(pywikibot.Error):
+
 """The wiki site returned an error message."""
+
 def __init__(self, code, info, **kwargs):
 """Save error dict returned by MW API."""
 self.code = code
@@ -67,6 +69,7 @@
 
 
 class Request(MutableMapping):
+
 """A request to a Site's api.php interface.
 
 Attributes of this object (except for the special parameters listed
@@ -121,6 +124,7 @@
 @param format: (optional) Defaults to "json"
 
 """
+
 def __init__(self, **kwargs):
 try:
 self.site = kwargs.pop("site")
@@ -277,7 +281,7 @@
 def submit(self):
 """Submit a query and parse the response.
 
-@return:  The data retrieved from api.php (a dict)
+@return: a dict containing data retrieved from api.php
 
 """
 while True:
@@ -469,7 +473,10 @@
 
 class CachedRequest(Request):
 def __init__(self, expiry, *args, **kwargs):
-""" expiry should be either a number of days or a datetime.timedelta 
object """
+"""Construct a CachedRequest object.
+
+@param expiry: either a number of days or a datetime.timedelta object
+"""
 super(CachedRequest, self).__init__(*args, **kwargs)
 if not isinstance(expiry, datetime.timedelta):
 expiry = datetime.timedelta(expiry)
@@ -479,7 +486,7 @@
 
 @staticmethod
 def _get_cache_dir():
-"""The base directory path for cache entries.
+"""Return the base directory path for cache entries.
 
 The directory will be created if it does not already exist.
 
@@ -508,11 +515,12 @@
 return dir
 
 def _uniquedescriptionstr(self):
-""" Unique description for the cache entry.
+"""Return unique description for the cache entry.
 
 If this is modified, please also update
 scripts/maintenance/cache.py to support
-the new key and all previous keys. """
+the new key and all previous keys.
+"""
 
 login_status = self.site._loginstatus
 
@@ -544,7 +552,7 @@
 return dt + self.expiry < datetime.datetime.now()
 
 def _load_cache(self):
-""" Return whether the cache can be used """
+"""Return whether the cache can be used."""
 try:
 with open(self._cachefile_path(), 'rb') as f:
 uniquedescr, self._data, self._cachetime = pickle.load(f)
@@ -561,7 +569,7 @@
 return False
 
 def _write_cache(self, data):
-""" writes data to self._cachefile_path() """
+"""Write data to self._cachefile_path()."""
 data = [self._uniquedescriptionstr(), data, datetime.datetime.now()]
 with open(self._cachefile_path(), 'wb') as f:
 pickle.dump(data, f)
@@ -575,6 +583,7 @@
 
 
 class QueryGenerator(object):
+
 """Base class for iterators that handle responses to API action=query.
 
 By default, the iterator will iterate each item in the query response,
@@ -590,11 +599,12 @@
 links. See the API documentation for specific query options.
 
 """
+
 def __init__(self, **kwargs):
-"""
-Constructor: kwargs are used to create a Request object;
-see that object's documentation for values. 'action'='query' is
-assumed.
+"""Construct a QueryGenerator object.
+
+kwargs are used to create a Request object; see that object's
+documentation for values. 'action'='query' is assumed.
 
 """
 if "action" in kwargs and kwargs["action"] != "query":
@@ -644,7 +654,7 @@
 def __modules(self):
 """
 Instance cache: hold the query data for paraminfo on
-querymodule=self.module at self.site
+querymodule=self.module at self.site.
 
 """
 if not hasattr(self.site, "_modules"):
@@ -653,13 +663,13 @@
 
 @__modules.deleter
 def __modules(self):
-"""Delete the instance cache - maybe we don't need it"""
+"""Delete the instance cache - maybe we don't need it."""
 if hasattr(self.site, "_modules"):
 del self.site._modules
 
 @property
 def _modules(self):
-"""Query api on self.site for paraminfo on querymodule=self.module"""
+"""Query api on self.site for paraminfo on querymodule=self.module."""
 if not set(self.module.split('|')) <= set(self.__modules.keys()):
  

[MediaWiki-commits] [Gerrit] [WIP] Add RepeatingGenerator - change (pywikibot/core)

2014-08-29 Thread Nullzero (Code Review)
Nullzero has uploaded a new change for review.

  https://gerrit.wikimedia.org/r/157056

Change subject: [WIP] Add RepeatingGenerator
..

[WIP] Add RepeatingGenerator

In compat, we have many generators such as logpages(), recentchanges()
with parameter `repeat`, while in core this parameter is missing.
RepeatingGenerator is a way to bring its functionality back.

Change-Id: I3da94de6bec0d5638f7be39597db90f7a1e7bc6d
---
M pywikibot/pagegenerators.py
1 file changed, 37 insertions(+), 0 deletions(-)


  git pull ssh://gerrit.wikimedia.org:29418/pywikibot/core 
refs/changes/56/157056/1

diff --git a/pywikibot/pagegenerators.py b/pywikibot/pagegenerators.py
index a46e27c..1479ac1 100644
--- a/pywikibot/pagegenerators.py
+++ b/pywikibot/pagegenerators.py
@@ -22,6 +22,7 @@
 import codecs
 import itertools
 import re
+import time
 import pywikibot
 from pywikibot import date, config, i18n
 from pywikibot.tools import deprecate_arg
@@ -983,6 +984,42 @@
 yield page.toggleTalkPage()
 
 
+def RepeatingGenerator(generator, sleep_duration=60, keyfunc=lambda x: x, 
total=None, **kwargs):
+"""Yield pages in live time.
+
+For example, to get pages in recentchanges in live time, call
+
+gen = RepeatingGenerator(site.recentchanges, 60, lambda x: x['revid'])
+
+Note that other keyword arguments not listed below will be passed
+to the generator function
+
+@param generator: a generator that will be queried
+@param sleep_duration: duration between each query
+@param keyfunc: a function returning key that will be used to detect 
duplicate entry
+@param total: total pages to be yielded
+@return: a generator
+"""
+# TODO: sort order by time
+seen = set()
+first_item = list(generator(total=1, **kwargs))
+if first_item:
+seen.add(keyfunc(first_item[0]))
+
+i = 0
+while i < total or total is None:
+for page in generator(**kwargs):
+if keyfunc(page) not in seen:
+i += 1
+seen.add(keyfunc(page))
+yield page
+if i == total:
+break
+else:
+break
+time.sleep(sleep_duration)
+
+
 @deprecate_arg("pageNumber", "step")
 @deprecate_arg("lookahead", None)
 def PreloadingGenerator(generator, step=50):

-- 
To view, visit https://gerrit.wikimedia.org/r/157056
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: newchange
Gerrit-Change-Id: I3da94de6bec0d5638f7be39597db90f7a1e7bc6d
Gerrit-PatchSet: 1
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Nullzero 

___
MediaWiki-commits mailing list
MediaWiki-commits@lists.wikimedia.org
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits


[MediaWiki-commits] [Gerrit] [WIP] Introduce appendtext / prependtext - change (pywikibot/core)

2014-12-17 Thread Nullzero (Code Review)
Nullzero has uploaded a new change for review.

  https://gerrit.wikimedia.org/r/180729

Change subject: [WIP] Introduce appendtext / prependtext
..

[WIP] Introduce appendtext / prependtext

Bug: T57054
Change-Id: I811b019523f21b014d78b514cbbac11573346e5f
---
M pywikibot/site.py
M scripts/i18n
2 files changed, 51 insertions(+), 29 deletions(-)


  git pull ssh://gerrit.wikimedia.org:29418/pywikibot/core 
refs/changes/29/180729/1

diff --git a/pywikibot/site.py b/pywikibot/site.py
index 8f82568..3d7f36e 100644
--- a/pywikibot/site.py
+++ b/pywikibot/site.py
@@ -3792,9 +3792,7 @@
 }
 
 @must_be(group='user')
-def editpage(self, page, summary, minor=True, notminor=False,
- bot=True, recreate=True, createonly=False, nocreate=False,
- watch=None):
+def editpage(self, page, summary, **kwargs):
 """Submit an edited Page object to be saved to the wiki.
 
 @param page: The Page to be saved; its .text property will be used
@@ -3818,42 +3816,66 @@
 @return: True if edit succeeded, False if it failed
 
 """
-text = page.text
-if text is None:
+kwargs['text'] = page.text
+kwargs['recreate'] = kwargs.get('recreate', True)
+if kwargs['text'] is None:
 raise Error("editpage: no text to be saved")
 try:
 lastrev = page.latestRevision()
 except NoPage:
 lastrev = None
-if not recreate:
+if not kwargs['recreate']:
 raise
-token = self.tokens['edit']
-self.lock_page(page)
-params = dict(action="edit",
-  title=page.title(withSection=False),
-  text=text, token=token, summary=summary)
-if bot:
-params['bot'] = ""
 if lastrev is not None:
 if lastrev not in page._revisions:
 self.loadrevisions(page)
-params['basetimestamp'] = page._revisions[lastrev].timestamp
-if minor:
+kwargs['basetimestamp'] = page._revisions[lastrev].timestamp
+return self.editpage_submit('edit', page, summary, **kwargs)
+
+def prependpage(self, page, text, summary, **kwargs):
+kwargs['prependtext'] = text
+return self.editpage_submit('prepend', page, summary, **kwargs)
+
+def appendpage(self, page, text, summary, **kwargs):
+kwargs['appendtext'] = text
+return self.editpage_submit('append', page, summary, **kwargs)
+
+def editpage_submit(self, meth, page, summary, **kwargs):
+token = self.tokens['edit']
+params = dict(action="edit",
+  title=page.title(withSection=False),
+  token=token, summary=summary)
+if 'text' in kwargs:
+params['text'] = kwargs['text']
+if 'prependtext' in kwargs:
+params['prependtext'] = kwargs['prependtext']
+if 'appendtext' in kwargs:
+params['appendtext'] = kwargs['appendtext']
+if 'basetimestamp' in kwargs:
+params['basetimestamp'] = kwargs['basetimestamp']
+if kwargs.get('bot', True):
+params['bot'] = ""
+if kwargs.get('minor', True):
 params['minor'] = ""
-elif notminor:
+elif kwargs.get('notminor', False):
 params['notminor'] = ""
-if recreate:
+if kwargs.get('recreate', True):
 params['recreate'] = ""
-if createonly:
+if kwargs.get('createonly', False):
 params['createonly'] = ""
-if nocreate:
+if kwargs.get('nocreate', False):
 params['nocreate'] = ""
+# Note: the default of this parameter is set in editpage() as well
+# If it needs to be changed, don't forget to change editpage()
+watch = kwargs.get('watch', None)
 if watch in ["watch", "unwatch", "preferences", "nochange"]:
 params['watchlist'] = watch
 elif watch:
 pywikibot.warning(
 u"editpage: Invalid watch value '%(watch)s' ignored."
 % locals())
+
+self.lock_page(page)
 req = api.Request(site=self, **params)
 while True:
 try:
@@ -3864,8 +3886,8 @@
 self.unlock_page(page)
 if err.code.endswith("anon") and self.logged_in():
 pywikibot.debug(
-u"editpage: received '%s' even though bot is logged in"
-% err.code,
+u"%spage: received '%s' even though bot is logged in"
+% (meth, err.code),
 _logger)
 if err.code in self._ep_errors:
 if isinstance(self._ep_errors[err.code], basestring):
@@ -3879,8 +3901,8 @@
 else:
 raise self._ep_errors