您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 
 
 

787 行
24 KiB

  1. #!/usr/bin/env python2.7
  2. # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
  3. # MIT License. See license.txt
  4. from __future__ import unicode_literals
  5. import sys, os
  6. import webnotes
  7. site_arg_optional = ['serve']
  8. def main():
  9. parsed_args = webnotes._dict(vars(setup_parser()))
  10. fn = get_function(parsed_args)
  11. if not parsed_args.get("sites_path"):
  12. parsed_args["sites_path"] = "."
  13. if not parsed_args.get("make_app"):
  14. if not parsed_args.get("site") and not fn in site_arg_optional:
  15. print "Site argument required"
  16. exit(1)
  17. if fn not in site_arg_optional and (fn != 'install' and not os.path.exists(parsed_args.get("site"))):
  18. print "Did not find folder '{}'. Are you in sites folder?".format(parsed_args.get("site"))
  19. exit(1)
  20. if parsed_args.get("site")=="all":
  21. for site in get_sites():
  22. args = parsed_args.copy()
  23. args["site"] = site
  24. webnotes.init(site)
  25. run(fn, args)
  26. else:
  27. if not fn in site_arg_optional:
  28. webnotes.init(parsed_args.get("site"))
  29. run(fn, parsed_args)
  30. else:
  31. run(fn, parsed_args)
  32. def cmd(fn):
  33. def new_fn(*args, **kwargs):
  34. import inspect
  35. fnargs, varargs, varkw, defaults = inspect.getargspec(fn)
  36. new_kwargs = {}
  37. for i, a in enumerate(fnargs):
  38. # should not pass an argument more than once
  39. if i >= len(args) and a in kwargs:
  40. new_kwargs[a] = kwargs.get(a)
  41. return fn(*args, **new_kwargs)
  42. return new_fn
  43. def run(fn, args):
  44. if isinstance(args.get(fn), (list, tuple)):
  45. out = globals().get(fn)(*args.get(fn), **args)
  46. else:
  47. out = globals().get(fn)(**args)
  48. return out
  49. def get_function(args):
  50. for fn, val in args.items():
  51. if (val or isinstance(val, list)) and globals().get(fn):
  52. return fn
  53. def get_sites():
  54. import os
  55. import conf
  56. return [site for site in os.listdir(conf.sites_dir)
  57. if not os.path.islink(os.path.join(conf.sites_dir, site))
  58. and os.path.isdir(os.path.join(conf.sites_dir, site))]
  59. def setup_parser():
  60. import argparse
  61. parser = argparse.ArgumentParser(description="Run webnotes utility functions")
  62. setup_install(parser)
  63. setup_utilities(parser)
  64. setup_translation(parser)
  65. setup_test(parser)
  66. parser.add_argument("site", nargs="?")
  67. # common
  68. parser.add_argument("-f", "--force", default=False, action="store_true",
  69. help="Force execution where applicable (look for [-f] in help)")
  70. parser.add_argument("-v", "--verbose", default=False, action="store_true", dest="verbose",
  71. help="Show verbose output where applicable")
  72. return parser.parse_args()
  73. def setup_install(parser):
  74. parser.add_argument("--make_app", default=False, action="store_true",
  75. help="Make a new application with boilerplate")
  76. parser.add_argument("--install", metavar="DB-NAME", nargs=1,
  77. help="Install a new db")
  78. parser.add_argument("--install_app", metavar="APP-NAME", nargs=1,
  79. help="Install a new app")
  80. parser.add_argument("--root-password", nargs=1,
  81. help="Root password for new app")
  82. parser.add_argument("--reinstall", default=False, action="store_true",
  83. help="Install a fresh app in db_name specified in conf.py")
  84. parser.add_argument("--restore", metavar=("DB-NAME", "SQL-FILE"), nargs=2,
  85. help="Restore from an sql file")
  86. parser.add_argument("--add_system_manager", nargs="+",
  87. metavar=("EMAIL", "[FIRST-NAME] [LAST-NAME]"), help="Add a user with all roles")
  88. def setup_test(parser):
  89. parser.add_argument("--run_tests", default=False, action="store_true",
  90. help="Run tests options [-d doctype], [-m module]")
  91. parser.add_argument("--app", metavar="APP-NAME", nargs=1,
  92. help="Run command for specified app")
  93. parser.add_argument("-d", "--doctype", metavar="DOCTYPE", nargs=1,
  94. help="Run command for specified doctype")
  95. parser.add_argument("-m", "--module", metavar="MODULE", nargs=1,
  96. help="Run command for specified module")
  97. def setup_utilities(parser):
  98. # update
  99. parser.add_argument("-u", "--update", nargs="*", metavar=("REMOTE", "BRANCH"),
  100. help="Perform git pull, run patches, sync schema and rebuild files/translations")
  101. parser.add_argument("--reload_gunicorn", default=False, action="store_true", help="reload gunicorn on update")
  102. parser.add_argument("--patch", nargs=1, metavar="PATCH-MODULE",
  103. help="Run a particular patch [-f]")
  104. parser.add_argument("-l", "--latest", default=False, action="store_true",
  105. help="Run patches, sync schema and rebuild files/translations")
  106. parser.add_argument("--sync_all", default=False, action="store_true",
  107. help="Reload all doctypes, pages, etc. using txt files [-f]")
  108. parser.add_argument("--update_all_sites", nargs="*", metavar=("REMOTE", "BRANCH"),
  109. help="Perform git pull, run patches, sync schema and rebuild files/translations")
  110. parser.add_argument("--reload_doc", nargs=3,
  111. metavar=('"MODULE"', '"DOCTYPE"', '"DOCNAME"'))
  112. # build
  113. parser.add_argument("-b", "--build", default=False, action="store_true",
  114. help="Minify + concatenate JS and CSS files, build translations")
  115. parser.add_argument("-w", "--watch", default=False, action="store_true",
  116. help="Watch and concatenate JS and CSS files as and when they change")
  117. # misc
  118. parser.add_argument("--backup", default=False, action="store_true",
  119. help="Take backup of database in backup folder [--with_files]")
  120. parser.add_argument("--move", default=False, action="store_true",
  121. help="Move site to different directory defined by --dest_dir")
  122. parser.add_argument("--dest_dir", nargs=1, metavar="DEST-DIR",
  123. help="Move site to different directory")
  124. parser.add_argument("--with_files", default=False, action="store_true",
  125. help="Also take backup of files")
  126. parser.add_argument("--domain", nargs="*",
  127. help="Get or set domain in Website Settings")
  128. parser.add_argument("--make_conf", nargs="*", metavar=("DB-NAME", "DB-PASSWORD"),
  129. help="Create new conf.py file")
  130. parser.add_argument("--make_custom_server_script", nargs=1, metavar="DOCTYPE",
  131. help="Create new conf.py file")
  132. parser.add_argument("--set_admin_password", metavar='ADMIN-PASSWORD', nargs=1,
  133. help="Set administrator password")
  134. parser.add_argument("--request", metavar='URL-ARGS', nargs=1, help="Run request as admin")
  135. parser.add_argument("--mysql", action="store_true", help="get mysql shell for a site")
  136. parser.add_argument("--serve", action="store_true", help="Run development server")
  137. parser.add_argument("--profile", action="store_true", help="enable profiling in development server")
  138. parser.add_argument("--smtp", action="store_true", help="Run smtp debug server",
  139. dest="smtp_debug_server")
  140. parser.add_argument("--python", action="store_true", help="get python shell for a site")
  141. parser.add_argument("--flush_memcache", action="store_true", help="flush memcached")
  142. parser.add_argument("--ipython", action="store_true", help="get ipython shell for a site")
  143. parser.add_argument("--get_site_status", action="store_true", help="Get site details")
  144. parser.add_argument("--update_site_config", nargs=1,
  145. metavar="site-CONFIG-JSON",
  146. help="Update site_config.json for a given site")
  147. parser.add_argument("--port", default=8000, type=int, help="port for development server")
  148. # clear
  149. parser.add_argument("--clear_web", default=False, action="store_true",
  150. help="Clear website cache")
  151. parser.add_argument("--build_sitemap", default=False, action="store_true",
  152. help="Build Website Sitemap")
  153. parser.add_argument("--clear_cache", default=False, action="store_true",
  154. help="Clear cache, doctype cache and defaults")
  155. parser.add_argument("--reset_perms", default=False, action="store_true",
  156. help="Reset permissions for all doctypes")
  157. # scheduler
  158. parser.add_argument("--run_scheduler", default=False, action="store_true",
  159. help="Trigger scheduler")
  160. parser.add_argument("--run_scheduler_event", nargs=1,
  161. metavar="all | daily | weekly | monthly",
  162. help="Run a scheduler event")
  163. # replace
  164. parser.add_argument("--replace", nargs=3,
  165. metavar=("SEARCH-REGEX", "REPLACE-BY", "FILE-EXTN"),
  166. help="Multi-file search-replace [-f]")
  167. # import/export
  168. parser.add_argument("--export_doc", nargs=2, metavar=('"DOCTYPE"', '"DOCNAME"'))
  169. parser.add_argument("--export_doclist", nargs=3, metavar=("DOCTYPE", "NAME", "PATH"),
  170. help="""Export doclist as json to the given path, use '-' as name for Singles.""")
  171. parser.add_argument("--export_csv", nargs=2, metavar=("DOCTYPE", "PATH"),
  172. help="""Dump DocType as csv""")
  173. parser.add_argument("--import_doclist", nargs=1, metavar="PATH",
  174. help="""Import (insert/update) doclist. If the argument is a directory, all files ending with .json are imported""")
  175. def setup_translation(parser):
  176. parser.add_argument("--build_message_files", default=False, action="store_true",
  177. help="Build message files for translation.")
  178. parser.add_argument("--get_untranslated", nargs=2, metavar=("LANG-CODE", "TARGET-FILE-PATH"),
  179. help="""Get untranslated strings for lang.""")
  180. parser.add_argument("--update_translations", nargs=3,
  181. metavar=("LANG-CODE", "UNTRANSLATED-FILE-PATH", "TRANSLATED-FILE-PATH"),
  182. help="""Update translated strings.""")
  183. # methods
  184. @cmd
  185. def make_app():
  186. from webnotes.utils.boilerplate import make_boilerplate
  187. make_boilerplate()
  188. # install
  189. @cmd
  190. def install(db_name, root_login="root", root_password=None, source_sql=None,
  191. admin_password = 'admin', verbose=True, force=False, site_config=None, reinstall=False):
  192. from webnotes.installer import install_db, install_app
  193. install_db(root_login=root_login, root_password=root_password, db_name=db_name, source_sql=source_sql,
  194. admin_password = admin_password, verbose=verbose, force=force, site_config=site_config, reinstall=reinstall)
  195. install_app("webnotes", verbose=verbose)
  196. webnotes.destroy()
  197. @cmd
  198. def install_app(app_name, verbose=False):
  199. from webnotes.installer import install_app
  200. webnotes.connect()
  201. install_app(app_name, verbose=verbose)
  202. webnotes.destroy()
  203. @cmd
  204. def reinstall(verbose=True):
  205. install(db_name=webnotes.conf.db_name, verbose=verbose, force=True, reinstall=True)
  206. @cmd
  207. def restore(db_name, source_sql, verbose=True, force=False):
  208. install(db_name, source_sql, verbose=verbose, force=force)
  209. @cmd
  210. def install_fixtures():
  211. from webnotes.install_lib.install import install_fixtures
  212. install_fixtures()
  213. webnotes.destroy()
  214. @cmd
  215. def add_system_manager(email, first_name=None, last_name=None):
  216. webnotes.connect()
  217. webnotes.profile.add_system_manager(email, first_name, last_name)
  218. webnotes.conn.commit()
  219. webnotes.destroy()
  220. # utilities
  221. @cmd
  222. def update(remote=None, branch=None, reload_gunicorn=False):
  223. pull(remote=remote, branch=branch)
  224. # maybe there are new framework changes, any consequences?
  225. reload(webnotes)
  226. build()
  227. latest()
  228. if reload_gunicorn:
  229. import subprocess
  230. subprocess.check_output("killall -HUP gunicorn".split())
  231. @cmd
  232. def latest(verbose=True):
  233. import webnotes.modules.patch_handler
  234. import webnotes.model.sync
  235. from webnotes.website import rebuild_config
  236. webnotes.connect()
  237. try:
  238. # run patches
  239. webnotes.local.patch_log_list = []
  240. webnotes.modules.patch_handler.run_all()
  241. if verbose:
  242. print "\n".join(webnotes.local.patch_log_list)
  243. # sync
  244. webnotes.model.sync.sync_all()
  245. # build website config if any changes in templates etc.
  246. rebuild_config()
  247. except webnotes.modules.patch_handler.PatchError, e:
  248. print "\n".join(webnotes.local.patch_log_list)
  249. raise
  250. finally:
  251. webnotes.destroy()
  252. @cmd
  253. def sync_all(force=False):
  254. import webnotes.model.sync
  255. webnotes.connect()
  256. webnotes.model.sync.sync_all(force=force)
  257. webnotes.destroy()
  258. @cmd
  259. def patch(patch_module, force=False):
  260. import webnotes.modules.patch_handler
  261. webnotes.connect()
  262. webnotes.local.patch_log_list = []
  263. webnotes.modules.patch_handler.run_single(patch_module, force=force)
  264. print "\n".join(webnotes.local.patch_log_list)
  265. webnotes.destroy()
  266. @cmd
  267. def update_all_sites(remote=None, branch=None, verbose=True):
  268. pull(remote, branch)
  269. # maybe there are new framework changes, any consequences?
  270. reload(webnotes)
  271. build()
  272. for site in get_sites():
  273. webnotes.init(site)
  274. latest(verbose=verbose)
  275. @cmd
  276. def reload_doc(module, doctype, docname, force=False):
  277. webnotes.connect()
  278. webnotes.reload_doc(module, doctype, docname, force=force)
  279. webnotes.conn.commit()
  280. webnotes.destroy()
  281. @cmd
  282. def build():
  283. import webnotes.build
  284. import webnotes
  285. webnotes.build.bundle(False)
  286. @cmd
  287. def watch():
  288. import webnotes.build
  289. webnotes.build.watch(True)
  290. @cmd
  291. def backup(with_files=False, verbose=True, backup_path_db=None, backup_path_files=None):
  292. from webnotes.utils.backups import scheduled_backup
  293. webnotes.connect()
  294. odb = scheduled_backup(ignore_files=not with_files, backup_path_db=backup_path_db, backup_path_files=backup_path_files)
  295. if verbose:
  296. from webnotes.utils import now
  297. print "database backup taken -", odb.backup_path_db, "- on", now()
  298. if with_files:
  299. print "files backup taken -", odb.backup_path_files, "- on", now()
  300. webnotes.destroy()
  301. return odb
  302. @cmd
  303. def move(dest_dir=None):
  304. import os
  305. if not dest_dir:
  306. raise Exception, "--dest_dir is required for --move"
  307. if not os.path.isdir(dest_dir):
  308. raise Exception, "destination is not a directory or does not exist"
  309. old_path = webnotes.utils.get_site()
  310. new_path = os.path.join(dest_dir, site)
  311. # check if site dump of same name already exists
  312. site_dump_exists = True
  313. count = 0
  314. while site_dump_exists:
  315. final_new_path = new_path + (count and str(count) or "")
  316. site_dump_exists = os.path.exists(final_new_path)
  317. count = int(count or 0) + 1
  318. os.rename(old_path, final_new_path)
  319. webnotes.destroy()
  320. return os.path.basename(final_new_path)
  321. @cmd
  322. def domain(host_url=None):
  323. webnotes.connect()
  324. if host_url:
  325. webnotes.conn.set_value("Website Settings", None, "subdomain", host_url)
  326. webnotes.conn.commit()
  327. else:
  328. print webnotes.conn.get_value("Website Settings", None, "subdomain")
  329. webnotes.destroy()
  330. @cmd
  331. def make_conf(db_name=None, db_password=None, site_config=None):
  332. from webnotes.install_lib.install import make_conf
  333. make_conf(db_name=db_name, db_password=db_password, site_config=site_config)
  334. @cmd
  335. def make_custom_server_script(doctype):
  336. from webnotes.core.doctype.custom_script.custom_script import make_custom_server_script_file
  337. webnotes.connect()
  338. make_custom_server_script_file(doctype)
  339. webnotes.destroy()
  340. # clear
  341. @cmd
  342. def clear_cache():
  343. import webnotes.sessions
  344. webnotes.connect()
  345. webnotes.clear_cache()
  346. webnotes.destroy()
  347. @cmd
  348. def clear_web():
  349. import webnotes.webutils
  350. webnotes.connect()
  351. webnotes.webutils.clear_cache()
  352. webnotes.destroy()
  353. @cmd
  354. def build_sitemap():
  355. from webnotes.website import rebuild_config
  356. webnotes.connect()
  357. rebuild_config()
  358. webnotes.destroy()
  359. @cmd
  360. def reset_perms():
  361. webnotes.connect()
  362. for d in webnotes.conn.sql_list("""select name from `tabDocType`
  363. where ifnull(istable, 0)=0 and ifnull(custom, 0)=0"""):
  364. webnotes.clear_cache(doctype=d)
  365. webnotes.reset_perms(d)
  366. webnotes.destroy()
  367. # scheduler
  368. @cmd
  369. def run_scheduler():
  370. from webnotes.utils.file_lock import create_lock, delete_lock
  371. import webnotes.utils.scheduler
  372. if create_lock('scheduler'):
  373. webnotes.connect()
  374. print webnotes.utils.scheduler.execute()
  375. delete_lock('scheduler')
  376. webnotes.destroy()
  377. @cmd
  378. def run_scheduler_event(event):
  379. import webnotes.utils.scheduler
  380. webnotes.connect()
  381. print webnotes.utils.scheduler.trigger(event)
  382. webnotes.destroy()
  383. # replace
  384. @cmd
  385. def replace(search_regex, replacement, extn, force=False):
  386. print search_regex, replacement, extn
  387. replace_code('.', search_regex, replacement, extn, force=force)
  388. # import/export
  389. @cmd
  390. def export_doc(doctype, docname):
  391. import webnotes.modules
  392. webnotes.connect()
  393. webnotes.modules.export_doc(doctype, docname)
  394. webnotes.destroy()
  395. @cmd
  396. def export_doclist(doctype, name, path):
  397. from webnotes.core.page.data_import_tool import data_import_tool
  398. webnotes.connect()
  399. data_import_tool.export_json(doctype, name, path)
  400. webnotes.destroy()
  401. @cmd
  402. def export_csv(doctype, path):
  403. from webnotes.core.page.data_import_tool import data_import_tool
  404. webnotes.connect()
  405. data_import_tool.export_csv(doctype, path)
  406. webnotes.destroy()
  407. @cmd
  408. def import_doclist(path, force=False):
  409. from webnotes.core.page.data_import_tool import data_import_tool
  410. webnotes.connect()
  411. data_import_tool.import_doclist(path, overwrite=force)
  412. webnotes.destroy()
  413. # translation
  414. @cmd
  415. def build_message_files():
  416. import webnotes.translate
  417. webnotes.connect()
  418. webnotes.translate.rebuild_all_translation_files()
  419. webnotes.destroy()
  420. @cmd
  421. def get_untranslated(lang, untranslated_file):
  422. import webnotes.translate
  423. webnotes.connect()
  424. webnotes.translate.get_untranslated(lang, untranslated_file)
  425. webnotes.destroy()
  426. @cmd
  427. def update_translations(lang, untranslated_file, translated_file):
  428. import webnotes.translate
  429. webnotes.connect()
  430. webnotes.translate.update_translations(lang, untranslated_file, translated_file)
  431. webnotes.destroy()
  432. # git
  433. @cmd
  434. def git(param):
  435. if isinstance(param, (list, tuple)):
  436. param = " ".join(param)
  437. import os
  438. os.system("""cd lib && git %s""" % param)
  439. os.system("""cd app && git %s""" % param)
  440. def get_remote_and_branch(remote=None, branch=None):
  441. if not (remote and branch):
  442. if not webnotes.conf.branch:
  443. raise Exception("Please specify remote and branch")
  444. remote = remote or "origin"
  445. branch = branch or webnotes.conf.branch
  446. webnotes.destroy()
  447. return remote, branch
  448. @cmd
  449. def pull(remote=None, branch=None):
  450. remote, branch = get_remote_and_branch(remote, branch)
  451. git(("pull", remote, branch))
  452. @cmd
  453. def push(remote=None, branch=None):
  454. remote, branch = get_remote_and_branch(remote, branch)
  455. git(("push", remote, branch))
  456. @cmd
  457. def status():
  458. git("status")
  459. @cmd
  460. def commit(message):
  461. git("""commit -a -m "%s" """ % message.replace('"', '\"'))
  462. @cmd
  463. def checkout(branch):
  464. git(("checkout", branch))
  465. @cmd
  466. def set_admin_password(admin_password):
  467. import webnotes
  468. webnotes.connect()
  469. webnotes.conn.sql("""update __Auth set `password`=password(%s)
  470. where user='Administrator'""", (admin_password,))
  471. webnotes.conn.commit()
  472. webnotes.destroy()
  473. @cmd
  474. def mysql():
  475. import webnotes
  476. import commands, os
  477. msq = commands.getoutput('which mysql')
  478. os.execv(msq, [msq, '-u', webnotes.conf.db_name, '-p'+webnotes.conf.db_password, webnotes.conf.db_name, '-h', webnotes.conf.db_host or "localhost", "-A"])
  479. webnotes.destroy()
  480. @cmd
  481. def python(site):
  482. import webnotes
  483. import commands, os
  484. python = commands.getoutput('which python')
  485. if site:
  486. os.environ["site"] = site
  487. os.environ["PYTHONSTARTUP"] = os.path.join(os.path.dirname(webnotes.__file__), "pythonrc.py")
  488. os.execv(python, [python])
  489. webnotes.destroy()
  490. @cmd
  491. def ipython():
  492. import webnotes
  493. webnotes.connect()
  494. import IPython
  495. IPython.embed()
  496. @cmd
  497. def smtp_debug_server():
  498. import commands, os
  499. python = commands.getoutput('which python')
  500. os.execv(python, [python, '-m', "smtpd", "-n", "-c", "DebuggingServer", "localhost:25"])
  501. @cmd
  502. def run_tests(app=None, module=None, doctype=None, verbose=False):
  503. import webnotes.test_runner
  504. ret = webnotes.test_runner.main(app and app[0], module and module[0], doctype and doctype[0], verbose)
  505. if len(ret.failures) > 0 or len(ret.errors) > 0:
  506. exit(1)
  507. @cmd
  508. def serve(port=8000, profile=False, site=None):
  509. import webnotes.app
  510. webnotes.app.serve(port=port, profile=profile, site=site)
  511. @cmd
  512. def request(args):
  513. import webnotes.handler
  514. webnotes.connect()
  515. webnotes.form_dict = webnotes._dict([a.split("=") for a in args.split("&")])
  516. webnotes.handler.execute_cmd(webnotes.form_dict.cmd)
  517. print webnotes.response
  518. webnotes.destroy()
  519. @cmd
  520. def flush_memcache():
  521. webnotes.cache().flush_all()
  522. def replace_code(start, txt1, txt2, extn, search=None, force=False):
  523. """replace all txt1 by txt2 in files with extension (extn)"""
  524. import webnotes.utils
  525. import os, re
  526. esc = webnotes.utils.make_esc('[]')
  527. if not search: search = esc(txt1)
  528. for wt in os.walk(start, followlinks=1):
  529. for fn in wt[2]:
  530. if fn.split('.')[-1]==extn:
  531. fpath = os.path.join(wt[0], fn)
  532. with open(fpath, 'r') as f:
  533. content = f.read()
  534. if re.search(search, content):
  535. res = search_replace_with_prompt(fpath, txt1, txt2, force)
  536. if res == 'skip':
  537. return 'skip'
  538. def search_replace_with_prompt(fpath, txt1, txt2, force=False):
  539. """ Search and replace all txt1 by txt2 in the file with confirmation"""
  540. from termcolor import colored
  541. with open(fpath, 'r') as f:
  542. content = f.readlines()
  543. tmp = []
  544. for c in content:
  545. if c.find(txt1) != -1:
  546. print fpath
  547. print colored(txt1, 'red').join(c[:-1].split(txt1))
  548. a = ''
  549. if force:
  550. c = c.replace(txt1, txt2)
  551. else:
  552. while a.lower() not in ['y', 'n', 'skip']:
  553. a = raw_input('Do you want to Change [y/n/skip]?')
  554. if a.lower() == 'y':
  555. c = c.replace(txt1, txt2)
  556. elif a.lower() == 'skip':
  557. return 'skip'
  558. tmp.append(c)
  559. with open(fpath, 'w') as f:
  560. f.write(''.join(tmp))
  561. print colored('Updated', 'green')
  562. @cmd
  563. def get_site_status(verbose=False):
  564. import webnotes
  565. import webnotes.utils
  566. from webnotes.profile import get_system_managers
  567. from webnotes.core.doctype.profile.profile import get_total_users, get_active_users, \
  568. get_website_users, get_active_website_users
  569. import json
  570. webnotes.connect()
  571. ret = {
  572. 'last_backup_on': webnotes.local.conf.last_backup_on,
  573. 'active_users': get_active_users(),
  574. 'total_users': get_total_users(),
  575. 'active_website_users': get_active_website_users(),
  576. 'website_users': get_website_users(),
  577. 'system_managers': "\n".join(get_system_managers()),
  578. 'default_company': webnotes.conn.get_default("company"),
  579. 'disk_usage': webnotes.utils.get_disk_usage(),
  580. 'working_directory': webnotes.local.site_path
  581. }
  582. # country, timezone, industry
  583. control_panel_details = webnotes.conn.get_value("Control Panel", "Control Panel",
  584. ["country", "time_zone", "industry"], as_dict=True)
  585. if control_panel_details:
  586. ret.update(control_panel_details)
  587. # basic usage/progress analytics
  588. for doctype in ("Company", "Customer", "Item", "Quotation", "Sales Invoice",
  589. "Journal Voucher", "Stock Ledger Entry"):
  590. key = doctype.lower().replace(" ", "_") + "_exists"
  591. ret[key] = 1 if webnotes.conn.count(doctype) else 0
  592. webnotes.destroy()
  593. if verbose:
  594. print json.dumps(ret, indent=1, sort_keys=True)
  595. return ret
  596. @cmd
  597. def update_site_config(site_config, verbose=False):
  598. import json
  599. if isinstance(site_config, basestring):
  600. site_config = json.loads(site_config)
  601. webnotes.conf.site_config.update(site_config)
  602. site_config_path = webnotes.get_conf_path(webnotes.conf.sites_dir)
  603. with open(site_config_path, "w") as f:
  604. json.dump(webnotes.conf.site_config, f, indent=1, sort_keys=True)
  605. webnotes.destroy()
  606. @cmd
  607. def bump(repo, bump_type):
  608. import json
  609. assert repo in ['lib', 'app']
  610. assert bump_type in ['minor', 'major', 'patch']
  611. def validate(repo_path):
  612. import git
  613. repo = git.Repo(repo_path)
  614. if repo.active_branch != 'master':
  615. raise Exception, "Current branch not master in {}".format(repo_path)
  616. def bump_version(version, version_type):
  617. import semantic_version
  618. v = semantic_version.Version(version)
  619. if version_type == 'minor':
  620. v.minor += 1
  621. elif version_type == 'major':
  622. v.major += 1
  623. elif version_type == 'patch':
  624. v.patch += 1
  625. return unicode(v)
  626. def add_tag(repo_path, version):
  627. import git
  628. repo = git.Repo(repo_path)
  629. repo.index.add(['config.json'])
  630. repo.index.commit('bumped to version {}'.format(version))
  631. repo.create_tag('v' + version, repo.head)
  632. def update_framework_requirement(version):
  633. with open('app/config.json') as f:
  634. config = json.load(f)
  635. config['requires_framework_version'] = '==' + version
  636. with open('app/config.json', 'w') as f:
  637. json.dump(config, f, indent=1, sort_keys=True)
  638. validate('lib/')
  639. validate('app/')
  640. if repo == 'app':
  641. with open('app/config.json') as f:
  642. config = json.load(f)
  643. new_version = bump_version(config['app_version'], bump_type)
  644. config['app_version'] = new_version
  645. with open('app/config.json', 'w') as f:
  646. json.dump(config, f, indent=1, sort_keys=True)
  647. add_tag('app/', new_version)
  648. elif repo == 'lib':
  649. with open('lib/config.json') as f:
  650. config = json.load(f)
  651. new_version = bump_version(config['framework_version'], bump_type)
  652. config['framework_version'] = new_version
  653. with open('lib/config.json', 'w') as f:
  654. json.dump(config, f, indent=1, sort_keys=True)
  655. add_tag('lib/', new_version)
  656. update_framework_requirement(new_version)
  657. bump('app', bump_type)
  658. if __name__=="__main__":
  659. main()