forked from oxwall/owr
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathowr.py
More file actions
executable file
·734 lines (553 loc) · 23.3 KB
/
owr.py
File metadata and controls
executable file
·734 lines (553 loc) · 23.3 KB
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
#!/usr/bin/env python
import argparse
import base64
import getpass
import os
import re
import sys
import shutil
import subprocess
import tempfile
import urllib2
SOURCE_URL_PREFIX = "https://raw.githubusercontent.com/oxwall/owr/master/sources"
COMPOSER_DOWNLOAD_URL = 'https://getcomposer.org/composer.phar'
def _is_file(file_path):
return file_path.startswith((".", "..", os.sep, "~"))
def _is_relative_path(file_path):
return file_path.startswith((".", ".."))
def _is_relative_url(url):
return not _is_absolute_url(url) and _is_relative_path(url)
def _is_absolute_url(url):
return url.startswith(("http://", "https://"))
def _get_ssh_url(url):
return url.replace('https://', 'git@').replace('http://', 'git@')
def ssh_url(f):
def wrapper(*args):
branch, url = f(*args)
if args[0]._arguments.ssh:
url = _get_ssh_url(url)
return branch, url
return wrapper
def _change_branch(directory, branch, is_quiet=True):
quiet = "--quiet" if is_quiet else ""
os.system(
("git --work-tree=%s --git-dir=%s fetch " + quiet + " origin %s") % (
directory + os.sep, os.path.join(directory, ".git"), branch
)
)
os.system(
("git --work-tree=%s --git-dir=%s checkout " + quiet + " origin/%s") % (
directory + os.sep, os.path.join(directory, ".git"), branch
)
)
def _log_operation(operation, repo_url, path, branch):
colors = {'blue': '\033[94m', 'red': '\033[91m', 'end': '\033[0m'}
repo_name = repo_url[repo_url.rindex("/") + 1:-4]
branch_color = colors['blue'] if branch == "master" else colors['red']
args = (
colors['blue'] + repo_name + colors['end'],
branch_color + branch + colors['end'],
colors['blue'] + path + colors['end']
)
if operation == "update":
print "Updating %s (%s) in %s" % args
elif operation == "clone":
print "Cloning %s (%s) to %s" % args
class SourceListParser:
_sourceListType = "global"
_defaultConfig = ["github.com/oxwall"]
_repoSection = {
"name": "plugins",
"prefix": None
}
records = {}
def __init__(self, arguments):
self._arguments = arguments
self._repoSection["config"] = self._defaultConfig
def _process_operation(self, command, base_path):
parts = map(str.strip, command.split(" "))
g_source_type = self._arguments.sourceType
def include(source):
if g_source_type == "file" and _is_file(source):
path = source
if _is_relative_path(source):
path = os.path.normpath(os.path.join(base_path, source))
return self._fetch_source(path, "file")
if _is_absolute_url(source):
url = source
elif _is_relative_url(source):
url = "%s/%s" % (base_path.rstrip("/"), source)
else:
url = "%s/%s" % (SOURCE_URL_PREFIX.rstrip("/"), source)
return self._fetch_source(url, "url")
operations = {"include": include}
try:
operation = operations[parts[0]]
args = parts[1:]
operation(*args)
except (IndexError, KeyError, TypeError):
return
def _process_section(self, section):
parts = map(str.strip, section.split(" "))
self._repoSection["name"] = parts[0]
if self._arguments.ssh:
parts[1] = parts[1].replace('/', ':')
self._repoSection["config"] = parts[1:] if len(parts) > 1 else self._defaultConfig
def _process_line(self, line):
parts = map(str.strip, line.split("="))
name = parts[0]
try:
alias = parts[1]
except IndexError:
alias = name
branch = "master"
reg_exp = re.compile("\((.*)\)")
args = re.findall(reg_exp, alias)
if args:
alias = re.sub(reg_exp, "", alias).strip()
name = re.sub(reg_exp, "", name).strip()
branch = args[0]
if self._repoSection["name"] not in self.records:
self.records[self._repoSection["name"]] = {}
self.records[self._repoSection["name"]][name] = {
"name": name.strip(), "alias": alias.strip(), "branch": branch.strip(),
"config": self._repoSection["config"]
}
def fetch(self):
return self._fetch_source(self._arguments.source, self._arguments.sourceType)
def _fetch_source(self, source, source_type):
data = []
if source_type == "url":
request = urllib2.Request(source)
if self._arguments.username:
base64string = base64.encodestring('%s:%s' % (self._arguments.username, self._arguments.password))[:-1]
request.add_header("Authorization", "Basic %s" % base64string)
try:
data = urllib2.urlopen(request)
except urllib2.HTTPError:
print "error: Source list not found: (%s)!!!" % source
exit()
base_path = source[0:source.rindex("/")] + "/"
else:
try:
data = open(source)
except IOError:
print "error: Could not open source list: (%s)!!!" % source
exit()
base_path = os.path.dirname(source)
for line in data:
line = line.strip()
if line and not line.startswith("#"):
if line.startswith("[") and line.endswith("]"):
self._process_section(line[1:-1].strip())
elif line.startswith("<") and line.endswith(">"):
self._process_operation(line[1:-1].strip(), base_path)
else:
self._process_line(line)
return self.records
class Arguments:
_sourcesUrlPrefix = SOURCE_URL_PREFIX
username = None
requirePassword = False
passwordString = None
password = None
ssh = False
command = None
path = None
source = "oxwall"
email = None
verbose = False
clearChanges = False
disableChmod = False
runDir = None
sourceType = "url"
def __init__(self, commands):
self._commands = dict(zip(map(lambda c: c.name, commands), commands))
self.source = "%s/%s" % (self._sourcesUrlPrefix, "oxwall")
self.runDir = os.getcwd()
def parse(self):
self.parse_args()
def parse_args(self):
parser = argparse.ArgumentParser()
parser.add_argument("command",
choices=self._commands.keys())
parser.add_argument("source",
nargs='?',
type=self._source,
default=self.source,
help="Source list file. Might be url, path or a reserved name ( oxwall, skadate, etc.. )")
parser.add_argument("path",
nargs='?',
default=".",
type=self._path,
help="Path to Oxwall Core root folder")
parser.add_argument('-u', '--user',
dest="username",
required=False,
help="github.com user name")
parser.add_argument('-e', '--email',
dest="email",
required=False,
help="github.com user email. Required for migrate command only")
parser.add_argument('-p', '--prompt',
dest="requirePassword",
action="store_true",
default=self.requirePassword,
required=False,
help="Pass this flag if password authorization is required")
parser.add_argument('--password',
dest="passwordString",
default=self.passwordString,
required=False,
help="Password string")
parser.add_argument('--ssh',
dest="ssh",
action="store_true",
default=self.ssh,
required=False,
help="Use ssh")
parser.add_argument('-v', '--verbose',
dest="verbose",
action="store_true",
default=self.verbose,
required=False,
help="Pass this flag if you want more verbose output")
parser.add_argument('-c', '--clear-changes',
dest="clearChanges",
action="store_true",
default=self.clearChanges,
required=False,
help="Pass this flag if you want to clear all changes you made. Cannot be undone!!!")
parser.add_argument('--disable-chmod',
dest="disableChmod",
action="store_true",
default=self.disableChmod,
required=False,
help="Pass this flag if you want to disable chmod!!!")
parser.parse_args(namespace=self)
def _path(self, path):
command = self._commands[self.command]
return command.validate_path(path.rstrip(os.sep), self)
def _source(self, source):
if self.passwordString:
self.password = self.passwordString
else:
if self.requirePassword and self.username:
try:
self.password = getpass.getpass("Enter password for user '%s': " % self.username)
except KeyboardInterrupt:
sys.exit(0)
if _is_file(source):
if not os.path.isfile(source):
raise argparse.ArgumentTypeError('Source list not found')
self.sourceType = "file"
return os.path.abspath(source)
self.sourceType = "url"
if not _is_absolute_url(source):
source = "%s/%s" % (self._sourcesUrlPrefix, source)
try:
request = urllib2.Request(source)
if self.username:
base64string = base64.encodestring('%s:%s' % (self.username, self.password))[:-1]
request.add_header("Authorization", "Basic %s" % base64string)
request.get_method = lambda: 'HEAD'
urllib2.urlopen(request)
except:
raise argparse.ArgumentTypeError('Source list not found')
return source
def read_config(self, name):
root_path = self.path if self.path else '.'
path = os.path.join(root_path, ".owr", name)
data = None
if os.path.isfile(path):
with open(path, "r") as f:
data = f.read()
return data
def read_configs(self):
username = self.read_config("username")
if not (username is None):
self.username = username
email = self.read_config("email")
if not (email is None):
self.email = email
require_password = self.read_config("require-password")
if not (require_password is None):
self.requirePassword = require_password
source = self.read_config("source")
if not (source is None):
self.source = source
def save_config(self, name, value):
if not os.path.isdir(self.path):
return
owr_dir = os.path.join(self.path, ".owr")
if not os.path.isdir(owr_dir):
os.mkdir(owr_dir)
path = os.path.join(owr_dir, name)
with open(path, "w+") as f:
f.write(str(value))
def save_configs(self):
self.save_config("username", self.username if self.username else "")
self.save_config("require-password", 1 if self.requirePassword else 0)
self.save_config("source", self.source if self.source else "")
self.save_config("email", self.email if self.email else "")
class Command:
composer_tmp_path = ''
def __init__(self, name):
self.name = name
def validate_path(self, path, args):
return path
def fetched(self, sections, args):
pass
def main(self, root_dir, url, args, branch):
pass
def item(self, path, url, args, branch, *opt):
pass
def composer(self, path):
if self.name not in ['update', 'clone'] or not os.path.exists('%s/composer.json' % path):
return None
if not self.composer_tmp_path:
composer = urllib2.urlopen(COMPOSER_DOWNLOAD_URL)
self.composer_tmp_path = tempfile.mkstemp()[1]
output = open(self.composer_tmp_path, 'wb')
output.write(composer.read())
output.close()
shutil.copyfile(self.composer_tmp_path, "%s/composer.phar" % path)
if os.path.exists('%s/composer.lock' % path):
sp = subprocess.Popen('php composer.phar update', shell=True, stdout=subprocess.PIPE, cwd=path)
else:
sp = subprocess.Popen('php composer.phar install', shell=True, stdout=subprocess.PIPE, cwd=path)
result = sp.communicate()[0]
print(result)
def clear_temp(self):
if self.name in ['update', 'clone']:
os.remove(self.composer_tmp_path)
def completed(self, root_dir, url, args):
pass
class UpdateCommand(Command):
def __init__(self):
Command.__init__(self, "update")
def validate_path(self, path, args):
if not os.path.isdir(os.path.join(path, ".git")):
raise argparse.ArgumentTypeError('Not a git repository')
return path
def main(self, root_dir, url, args, branch):
quiet = ""
if not args.verbose:
_log_operation("update", url, root_dir, branch)
quiet = "--quiet"
abs_path = os.path.abspath(root_dir)
os.system(("git --work-tree=%s --git-dir=%s pull " + quiet + " origin master") % (
abs_path + os.sep, os.path.join(abs_path, ".git"))
)
if args.clearChanges:
os.system(("git --work-tree=%s --git-dir=%s checkout " + quiet + " -- .") % (
abs_path + os.sep, os.path.join(abs_path, ".git"))
)
if branch != "master":
_change_branch(abs_path, branch, not args.verbose)
def item(self, path, url, args, branch, create=True, *opt):
quiet = ""
if not args.verbose:
quiet = "--quiet"
if os.path.isdir(path):
if not args.verbose:
_log_operation("update", url, path, branch)
if args.clearChanges:
os.system(("git --work-tree=%s --git-dir=%s checkout " + quiet + " -- .") % (
path + os.sep, os.path.join(path, ".git"))
)
# Checkout master branch
os.system(("git --work-tree=%s --git-dir=%s checkout " + quiet + " master") % (
path + os.sep, os.path.join(path, ".git"))
)
# Pull master branch
os.system(("git --work-tree=%s --git-dir=%s pull " + quiet + " origin master") % (
path + os.sep, os.path.join(path, ".git"))
)
elif create:
if not args.verbose:
_log_operation("clone", url, path, branch)
os.system("git clone " + quiet + " %s %s" % (url, path))
if branch != "master":
_change_branch(path, branch, not args.verbose)
class CloneCommand(Command):
def __init__(self):
Command.__init__(self, "clone")
def validate_path(self, path, args):
shall = True
if os.path.isdir(path) and os.listdir(path):
shall = raw_input("%s (Y/n): " % "Destination folder is not empty. Do you want to continue?").lower() == 'y'
if not shall:
sys.exit(0)
if os.path.isdir(path) and os.path.isdir(os.path.join(path, ".git")):
raise argparse.ArgumentTypeError('Destination folder should not contain git repository')
return path
def main(self, root_dir, url, args, branch):
quiet = ""
if not args.verbose:
_log_operation("clone", url, root_dir, branch)
quiet = "--quiet"
if os.path.isdir(root_dir):
tmp_dir = tempfile.mkdtemp()
os.system(("git clone " + quiet + " --no-checkout %s %s") % (url, tmp_dir))
shutil.move(os.path.join(tmp_dir, ".git"), os.path.join(root_dir, ".git"))
os.chdir(root_dir)
os.system("git reset " + quiet + " --hard HEAD")
shutil.rmtree(tmp_dir)
else:
os.system("git clone " + quiet + " %s %s" % (url, root_dir))
if branch != "master":
_change_branch(root_dir, branch, not args.verbose)
os.chdir(args.runDir)
def item(self, path, url, args, branch, *opt):
quiet = ""
if not args.verbose:
_log_operation("clone", url, path, branch)
quiet = "--quiet"
os.system("git clone " + quiet + " %s %s" % (url, path))
if branch != "master":
_change_branch(path, branch, not args.verbose)
def completed(self, root_dir, url, args):
config_file = os.path.join(root_dir, "ow_includes", "config.php")
shutil.copyfile(os.path.join(root_dir, "ow_includes", "config.php.default"), config_file)
templatec_path = os.path.join(root_dir, "ow_smarty", "template_c")
if not os.path.isdir(templatec_path):
os.mkdir(templatec_path)
if not args.disableChmod:
os.system("chmod 777 %s" % config_file)
os.system("chmod -R 777 %s" % os.path.join(root_dir, "ow_userfiles"))
os.system("chmod -R 777 %s" % os.path.join(root_dir, "ow_pluginfiles"))
os.system("chmod -R 777 %s" % os.path.join(root_dir, "ow_static"))
os.system("chmod -R 777 %s" % os.path.join(root_dir, "ow_log"))
os.system("chmod -R 777 %s" % templatec_path)
class MigrateCommand(Command):
def __init__(self):
Command.__init__(self, "migrate")
def validate_path(self, path, args):
if not os.path.isfile(os.path.join(path, "ow_version.xml")):
raise argparse.ArgumentTypeError('Oxwall based software not found')
return path
def main(self, root_dir, url, args, branch):
if not args.username:
print "error: Github user name is required !!!"
exit()
if not args.email:
print "error: Github user email is required !!!"
exit()
def item(self, path, url, args, *opt):
if not os.path.isdir(path):
return
tmp_dir = tempfile.mkdtemp()
os.chdir(tmp_dir)
os.system("git clone %s %s" % (url, tmp_dir))
os.system("git config user.email %s" % args.email)
os.system("git config user.name %s" % args.username)
os.system("cp -r %s %s" % (os.path.join(path, "*"), tmp_dir + os.sep))
os.system("git add .")
os.system('git ci -m "Source code"')
os.system("git push -u origin master")
os.chdir(args.runDir)
os.system("rm -rf %s" % tmp_dir)
# not completed
class InfoCommand(Command):
def __init__(self):
Command.__init__(self, "info")
self.records = []
def validate_path(self, path, args):
if not os.path.isdir(os.path.join(path, ".owr")):
raise argparse.ArgumentTypeError('owr information not found')
return path
def fetched(self, sections, args):
pass
def completed(self, root_dir, url, args):
pass
class Builder:
_arguments = None
_auth = None
_auth_prefix = None
_commands = {}
_parser = None
_sections = None
_sectionFolders = {
"plugins": "ow_plugins",
"themes": "ow_themes"
}
def __init__(self, arguments, commands):
self._parser = SourceListParser(arguments)
self._arguments = arguments
self._commands = dict(zip(map(lambda c: c.name, commands), commands))
def auth(self):
self._auth_prefix = ""
if self._arguments.username:
self._auth = self._arguments.username
if self._arguments.password:
self._auth = "%s:%s" % (self._arguments.username, urllib2.quote(self._arguments.password))
self._auth_prefix = "%s@" % self._auth
@ssh_url
def core(self):
try:
core_record = self._sections["core"].values()[0]
del self._sections["core"]
core_branch = core_record["branch"]
core_url = "https://%s%s/%s.git" % (self._auth_prefix, core_record["config"][0], core_record["name"])
except KeyError:
core_branch = "master"
core_url = "https://github.com/oxwall/oxwall.git"
return core_branch, core_url
@ssh_url
def install(self):
try:
install_record = self._sections["install"].values()[0]
del self._sections["install"]
install_branch = install_record["branch"]
install_url = "https://%s%s/%s.git" % (
self._auth_prefix, install_record["config"][0], install_record["name"])
except KeyError:
install_branch = "master"
install_url = "https://github.com/oxwall/install.git"
return install_branch, install_url
def records(self):
r = []
for sectionName in self._sections:
records = self._sections[sectionName]
try:
dir_name = self._sectionFolders[sectionName]
except IndexError:
continue
for name in records:
record = records[name]
path = os.path.abspath(os.path.join(self._arguments.path, dir_name, record["alias"]))
repo_prefix = record["config"][0] # repository prefix
url = "https://%s%s/%s.git" % (self._auth_prefix, repo_prefix, record["name"])
if self._arguments.ssh:
url = _get_ssh_url(url)
r.append({'path': path, 'url': url, 'branch': record['branch']})
return r
def process(self):
command = self._commands[self._arguments.command]
self._sections = self._parser.fetch()
command.fetched(self._sections, self._arguments)
self.auth()
core_branch, core_url = self.core()
command.main(os.path.abspath(self._arguments.path), core_url, self._arguments, core_branch)
command.composer(os.path.abspath(self._arguments.path))
install_branch, install_url = self.install()
command.item(os.path.abspath(os.path.join(self._arguments.path, "ow_install")), install_url, self._arguments,
install_branch, False)
records = self.records()
for r in records:
command.item(r['path'], r['url'], self._arguments, r['branch'])
command.composer(r['path'])
command.clear_temp()
command.completed(self._arguments.path, core_url, self._arguments)
def main():
commands = [CloneCommand(), UpdateCommand(), MigrateCommand()]
arguments = Arguments(commands)
arguments.read_configs()
arguments.parse()
builder = Builder(arguments, commands)
builder.process()
arguments.save_configs()
print "\n%s command was completed !!!" % arguments.command
if __name__ == "__main__":
main()