Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

wnf.py 23 KiB

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