-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmwiki-sak
executable file
·193 lines (167 loc) · 7.1 KB
/
mwiki-sak
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# MediaWiki command-line Swiss Army Knife. Run with --help to see more.
# https://github.com/OpenTechStrategies/csv2wiki/blob/master/mwiki-sak
#
# Copyright (C) 2017 Open Tech Strategies, LLC
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
__doc__ = """\
mwiki-sak: the MediaWiki Swiss Army Knife (command-line access to MediaWiki)
Usage: mwiki-sak -c CONFIG_FILE [OPTIONS] SUBCOMMAND [ARGUMENTS]
CONFIG_FILE has the same format as cvs2wiki's config file, but only
the wiki credentials fields are used.
Subcommands:
list: List all pages in the wiki
delete -f infile | PAGE1 [PAGE2...]: Delete specified pages
Options:
-f FILE | --infile FILE: Read args from FILE, one per line
mwiki-sak is free / open source software under the AGPL-3.0 license.
Please run with --version option for details.
"""
import mwclient
import getopt
import os
import sys
import configparser
import warnings
import requests # for exception matching
def usage(errout=False):
"""Print a message explaining how to use this script.
Print to stdout, unless ERROUT, in which case print to stderr."""
out = sys.stderr if errout else sys.stdout
out.write(__doc__)
def version(errout=False):
"""Print a message explaining how to use this script.
Print to stdout, unless ERROUT, in which case print to stderr."""
out = sys.stderr if errout else sys.stdout
out.write("""mwiki-sak version 1.0.0.
Copyright (C) 2017, 2018 Open Tech Strategies, LLC
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.\n""")
def main():
config = None
infile = None
try:
opts, args = getopt.getopt(sys.argv[1:],
'hv?c:f:',
["help",
"version",
"usage",
"infile=",
"config=",])
except getopt.GetoptError as err:
sys.stderr.write("ERROR: '%s'\n" % err)
usage(errout=True)
sys.exit(2)
for o, a in opts:
if o in ("-h", "-?", "--help", "--usage",):
usage()
sys.exit(0)
elif o in ("-v", "--version",):
version()
sys.exit(0)
elif o in ("-f", "--infile",):
infile = a
elif o in ("-c", "--config",):
config = configparser.ConfigParser()
config.read(a)
else:
sys.stderr.write("ERROR: unrecognized option '%s'\n" % o)
sys.exit(2)
wiki_url = config.get('default', 'wiki_url')
username = config.get('default', 'username')
password = config.get('default', 'password')
path_to_api = config.get('default', 'path_to_api', fallback="/")
# Connect to the site.
try:
site_conn = mwclient.Site(wiki_url.split("://"), path=path_to_api)
except requests.exceptions.HTTPError as err:
sys.stderr.write("ERROR: failed to connect to wiki URL '%s'\n" % wiki_url)
sys.stderr.write(" Error details:\n")
sys.stderr.write(" ('%s')\n" % err)
sys.exit(1)
try:
site_conn.login(username, password)
except mwclient.errors.LoginError as err:
sys.stderr.write("ERROR: Unable to log in to wiki; "
"check that username and password are correct.\n")
sys.stderr.write(" Error details:\n")
sys.stderr.write(" ('%s')\n" % err)
sys.exit(1)
# Subcommand dispatch.
if len(args) < 1:
sys.stderr.write("ERROR: subcommand argument required.\n")
usage(True)
sys.exit(1)
elif args[0].lower() == "help":
usage()
elif args[0].lower() == "list":
# This is basically the command-line equivalent of
# wiki.example.com/api.php?action=query&list=allpages
#
# Except we're going to print them out in sorted order,
# because a common use case is to get a list of pages, delete
# some of them, and then get a list again to make sure that
# exactly the ones requested to be deleted were deleted. To
# do that comparison, it helps to have the list sorted. The
# same logic probably applies to other uses of page lists.
page_names = []
for page in site_conn.pages:
page_names.append(page.name)
page_names.sort()
for page_name in page_names:
print("%s" % page_name)
elif args[0].lower() == "delete":
if len(args) == 1 and infile is None:
sys.stderr.write(
"ERROR: 'delete' requires arguments or the --infile option\n")
sys.exit(1)
if len(args) > 1 and infile is not None:
sys.stderr.write(
"ERROR: cannot combine command-line arguments with --infile\n")
sys.exit(1)
if len(args) > 1:
for page_name in args[1:]:
page = site_conn.pages[page_name]
try:
page.delete()
except mwclient.errors.APIError as e:
sys.stderr.write(
"ERROR: unable to delete page '%s':\n %s\n"
% (page_name, e.info))
else:
with open(infile) as infile_fp:
for line in infile_fp:
page = site_conn.pages[line.rstrip('\n')]
try:
page.delete()
# Deleting the page in the wiki doesn't delete
# the page object here, so page.name can still
# be dereferenced.
print("DELETED PAGE '%s'" % page.name)
except mwclient.errors.APIError as e:
raise Exception(
"ERROR: unable to delete page: '%s'" % e.info)
if __name__ == '__main__':
main()