You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

507 lines
14 KiB

  1. #!/usr/bin/env python
  2. # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd.
  3. # MIT License. See license.txt
  4. from __future__ import unicode_literals
  5. import os, sys
  6. def replace_code(start, txt1, txt2, extn, search=None, force=False):
  7. """replace all txt1 by txt2 in files with extension (extn)"""
  8. import webnotes.utils
  9. import os, re
  10. esc = webnotes.utils.make_esc('[]')
  11. if not search: search = esc(txt1)
  12. for wt in os.walk(start, followlinks=1):
  13. for fn in wt[2]:
  14. if fn.split('.')[-1]==extn:
  15. fpath = os.path.join(wt[0], fn)
  16. with open(fpath, 'r') as f:
  17. content = f.read()
  18. if re.search(search, content):
  19. res = search_replace_with_prompt(fpath, txt1, txt2, force)
  20. if res == 'skip':
  21. return 'skip'
  22. def search_replace_with_prompt(fpath, txt1, txt2, force=False):
  23. """ Search and replace all txt1 by txt2 in the file with confirmation"""
  24. from termcolor import colored
  25. with open(fpath, 'r') as f:
  26. content = f.readlines()
  27. tmp = []
  28. for c in content:
  29. if c.find(txt1) != -1:
  30. print fpath
  31. print colored(txt1, 'red').join(c[:-1].split(txt1))
  32. a = ''
  33. if force:
  34. c = c.replace(txt1, txt2)
  35. else:
  36. while a.lower() not in ['y', 'n', 'skip']:
  37. a = raw_input('Do you want to Change [y/n/skip]?')
  38. if a.lower() == 'y':
  39. c = c.replace(txt1, txt2)
  40. elif a.lower() == 'skip':
  41. return 'skip'
  42. tmp.append(c)
  43. with open(fpath, 'w') as f:
  44. f.write(''.join(tmp))
  45. print colored('Updated', 'green')
  46. def pull(remote, branch, build=False):
  47. os.system('cd lib && git pull %s %s' % (remote, branch))
  48. os.system('cd app && git pull %s %s' % (remote, branch))
  49. if build: rebuild()
  50. def rebuild():
  51. # build js / css
  52. from webnotes import build
  53. build.bundle(False)
  54. def apply_latest_patches():
  55. import webnotes.modules.patch_handler
  56. webnotes.modules.patch_handler.run_all()
  57. print '\n'.join(webnotes.modules.patch_handler.log_list)
  58. def sync_all(force=0):
  59. import webnotes.model.sync
  60. webnotes.model.sync.sync_all(force)
  61. def update_erpnext(remote='origin', branch='master'):
  62. pull(remote, branch)
  63. from webnotes.utils import execute_in_shell
  64. execute_in_shell("lib/wnf.py --patch_sync_build", verbose=1)
  65. def patch_sync_build():
  66. patch_sync()
  67. rebuild()
  68. def patch_sync():
  69. apply_latest_patches()
  70. import webnotes.modules.patch_handler
  71. for l in webnotes.modules.patch_handler.log_list:
  72. if "failed: STOPPED" in l:
  73. return
  74. sync_all()
  75. clear_cache()
  76. def clear_cache():
  77. import webnotes.sessions
  78. webnotes.sessions.clear_cache()
  79. def append_future_import():
  80. """appends from __future__ import unicode_literals to py files if necessary"""
  81. import os
  82. import conf
  83. conf_path = os.path.abspath(conf.__file__)
  84. if conf_path.endswith("pyc"):
  85. conf_path = conf_path[:-1]
  86. base_path = os.path.dirname(conf_path)
  87. for path, folders, files in os.walk(base_path):
  88. for f in files:
  89. if f.endswith('.py'):
  90. file_path = os.path.join(path, f)
  91. with open(file_path, 'r') as pyfile:
  92. content = pyfile.read()
  93. future_import = 'from __future__ import unicode_literals'
  94. if future_import in content: continue
  95. content = content.split('\n')
  96. idx = -1
  97. for c in content:
  98. idx += 1
  99. if c and not c.startswith('#'):
  100. break
  101. content.insert(idx, future_import)
  102. content = "\n".join(content)
  103. with open(file_path, 'w') as pyfile:
  104. pyfile.write(content)
  105. def setup_options():
  106. from optparse import OptionParser
  107. parser = OptionParser()
  108. # install
  109. parser.add_option('--install', nargs=2, metavar = "NEW_DB_NAME SOURCE_PATH",
  110. help="install db")
  111. parser.add_option('--install_fresh', nargs=1, metavar = "NEW_DB_NAME",
  112. help="install fresh db")
  113. parser.add_option('--make_demo', default=False, action="store_true",
  114. help="install in database 'demo'")
  115. # update
  116. parser.add_option("-u", "--update",
  117. help="Pull, run latest patches and sync all",
  118. default=False, action="store_true", metavar="ORIGIN BRANCH")
  119. parser.add_option("--backup", help="Takes backup of database in backup folder",
  120. default=False, action="store_true")
  121. # build
  122. parser.add_option("-b", "--build", default=False, action="store_true",
  123. help="minify + concat js files")
  124. parser.add_option("-w", "--watch", default=False, action="store_true",
  125. help="watch and minify + concat js files, if necessary")
  126. parser.add_option("--no_cms", default=False, action="store_true",
  127. help="do not build wn-web.js and wn-css.js")
  128. parser.add_option("--docs", default=False, action="store_true",
  129. help="Build docs")
  130. parser.add_option("-d", "--db",
  131. dest="db_name",
  132. help="Apply the patches on given db")
  133. parser.add_option("--password",
  134. help="Password for given db", nargs=1)
  135. parser.add_option("--clear_web", default=False, action="store_true",
  136. help="clear web cache")
  137. parser.add_option("--clear_cache", default=False, action="store_true",
  138. help="clear cache")
  139. parser.add_option("--clear_defaults", default=False, action="store_true",
  140. help="clear cache of defaults")
  141. parser.add_option("--domain", metavar="DOMAIN",
  142. help="store domain in Website Settings", nargs=1)
  143. # git
  144. parser.add_option("--status", default=False, action="store_true",
  145. help="git status")
  146. parser.add_option("--git", nargs=1, default=False,
  147. metavar = "git options",
  148. help="run git with options in both repos")
  149. parser.add_option("--pull", nargs=2, default=False,
  150. metavar = "remote branch",
  151. help="git pull (both repos)")
  152. parser.add_option("-c", "--commit", nargs=1, default=False,
  153. metavar = "commit both repos",
  154. help="git commit -a -m [comment]")
  155. parser.add_option("-p", "--push", default=False,
  156. action="store_true",
  157. metavar = "remote branch",
  158. help="git push (both repos) [remote] [branch]")
  159. parser.add_option("--checkout", nargs=1, default=False,
  160. metavar = "branch",
  161. help="git checkout [branch]")
  162. parser.add_option("-l", "--latest",
  163. action="store_true", dest="run_latest", default=False,
  164. help="Apply the latest patches")
  165. # patch
  166. parser.add_option("--patch", nargs=1, dest="patch_list",
  167. metavar='patch_module',
  168. action="append",
  169. help="Apply patch")
  170. parser.add_option("-f", "--force",
  171. action="store_true", dest="force", default=False,
  172. help="Force Apply all patches specified using option -p or --patch")
  173. parser.add_option('--reload_doc', nargs=3, metavar = "module doctype docname",
  174. help="reload doc")
  175. parser.add_option('--export_doc', nargs=2, metavar = "doctype docname",
  176. help="export doc")
  177. # diff
  178. parser.add_option('--diff_ref_file', nargs=0, \
  179. help="Get missing database records and mismatch properties, with file as reference")
  180. parser.add_option('--diff_ref_db', nargs=0, \
  181. help="Get missing .txt files and mismatch properties, with database as reference")
  182. # scheduler
  183. parser.add_option('--run_scheduler', default=False, action="store_true",
  184. help="Trigger scheduler")
  185. parser.add_option('--run_scheduler_event', nargs=1, metavar="[all|daily|weekly|monthly]",
  186. help="Run scheduler event")
  187. # misc
  188. parser.add_option("--replace", nargs=3, default=False,
  189. metavar = "search replace_by extension",
  190. help="file search-replace")
  191. parser.add_option("--sync_all", help="Synchronize all DocTypes using txt files",
  192. nargs=0)
  193. parser.add_option("--sync", help="Synchronize given DocType using txt file",
  194. nargs=2, metavar="module doctype (use their folder names)")
  195. parser.add_option("--patch_sync_build", action="store_true", default=False,
  196. help="run latest patches, sync all and rebuild js css")
  197. parser.add_option("--patch_sync", action="store_true", default=False,
  198. help="run latest patches, sync all")
  199. parser.add_option("--cleanup_data", help="Cleanup test data", default=False,
  200. action="store_true")
  201. parser.add_option("--append_future_import", default=False, action="store_true",
  202. help="append from __future__ import unicode literals to py files")
  203. parser.add_option("--build_message_files", default=False, action="store_true",
  204. help="Build message files for translation")
  205. parser.add_option('--export_messages', nargs=2, metavar="LANG FILENAME",
  206. help="""Export all messages for a language to translation in a csv file.
  207. Example, lib/wnf.py --export_messages hi hindi.csv""")
  208. parser.add_option('--import_messages', nargs=2, metavar="LANG FILENAME",
  209. help="""Import messages for a language and make language files.
  210. Example, lib/wnf.py --import_messages hi hindi.csv""")
  211. parser.add_option('--google_translate', nargs=3, metavar="LANG INFILE OUTFILE",
  212. help="""Auto translate using Google Translate API""")
  213. parser.add_option('--translate', nargs=1, metavar="LANG",
  214. help="""Rebuild translation for the given langauge and
  215. use Google Translate to tranlate untranslated messages. use "all" """)
  216. parser.add_option("--reset_perms", default=False, action="store_true",
  217. help="Reset permissions for all doctypes.")
  218. return parser.parse_args()
  219. def run():
  220. sys.path.append('.')
  221. sys.path.append('lib')
  222. sys.path.append('app')
  223. (options, args) = setup_options()
  224. # build
  225. if options.build:
  226. from webnotes import build
  227. if options.no_cms:
  228. cms_make = False
  229. else:
  230. cms_make = True
  231. build.bundle(False, cms_make)
  232. return
  233. elif options.watch:
  234. from webnotes import build
  235. build.watch(True)
  236. return
  237. # code replace
  238. elif options.replace:
  239. print options.replace
  240. replace_code('.', options.replace[0], options.replace[1], options.replace[2], force=options.force)
  241. return
  242. # git
  243. elif options.status:
  244. os.chdir('lib')
  245. os.system('git status')
  246. os.chdir('../app')
  247. os.system('git status')
  248. return
  249. elif options.git:
  250. os.chdir('lib')
  251. os.system('git %s' % options.git)
  252. os.chdir('../app')
  253. os.system('git %s' % options.git)
  254. return
  255. import webnotes
  256. import conf
  257. from webnotes.db import Database
  258. import webnotes.modules.patch_handler
  259. webnotes.print_messages = True
  260. # connect
  261. if options.db_name is not None:
  262. if options.password:
  263. webnotes.connect(options.db_name, options.password)
  264. else:
  265. webnotes.connect(options.db_name)
  266. elif not any([options.install, options.pull, options.install_fresh]):
  267. webnotes.connect(conf.db_name)
  268. if options.pull:
  269. pull(options.pull[0], options.pull[1], build=True)
  270. elif options.commit:
  271. os.chdir('lib')
  272. os.system('git commit -a -m "%s"' % (options.commit))
  273. os.chdir('../app')
  274. os.system('git commit -a -m "%s"' % (options.commit))
  275. elif options.push:
  276. if not args:
  277. args = ["origin", conf.branch]
  278. os.chdir('lib')
  279. os.system('git push %s %s' % (args[0], args[1]))
  280. os.chdir('../app')
  281. os.system('git push %s %s' % (args[0], args[1]))
  282. elif options.checkout:
  283. os.chdir('lib')
  284. os.system('git checkout %s' % options.checkout)
  285. os.chdir('../app')
  286. os.system('git checkout %s' % options.checkout)
  287. # patch
  288. elif options.patch_list:
  289. # clear log
  290. webnotes.modules.patch_handler.log_list = []
  291. # run individual patches
  292. for patch in options.patch_list:
  293. webnotes.modules.patch_handler.run_single(\
  294. patchmodule = patch, force = options.force)
  295. print '\n'.join(webnotes.modules.patch_handler.log_list)
  296. # reload
  297. elif options.reload_doc:
  298. webnotes.modules.patch_handler.reload_doc(\
  299. {"module":options.reload_doc[0], "dt":options.reload_doc[1], "dn":options.reload_doc[2]})
  300. print '\n'.join(webnotes.modules.patch_handler.log_list)
  301. elif options.export_doc:
  302. from webnotes.modules import export_doc
  303. export_doc(options.export_doc[0], options.export_doc[1])
  304. # run all pending
  305. elif options.run_latest:
  306. apply_latest_patches()
  307. elif options.install:
  308. from webnotes.install_lib.install import Installer
  309. inst = Installer('root')
  310. inst.import_from_db(options.install[0], source_path=options.install[1],
  311. verbose = 1)
  312. elif options.install_fresh:
  313. from webnotes.install_lib.install import Installer
  314. inst = Installer('root')
  315. inst.import_from_db(options.install_fresh, verbose = 1)
  316. elif options.make_demo:
  317. import utilities.make_demo
  318. utilities.make_demo.make()
  319. elif options.diff_ref_file is not None:
  320. import webnotes.modules.diff
  321. webnotes.modules.diff.diff_ref_file()
  322. elif options.diff_ref_db is not None:
  323. import webnotes.modules.diff
  324. webnotes.modules.diff.diff_ref_db()
  325. elif options.run_scheduler:
  326. import webnotes.utils.scheduler
  327. print webnotes.utils.scheduler.execute()
  328. elif options.run_scheduler_event is not None:
  329. import webnotes.utils.scheduler
  330. print webnotes.utils.scheduler.trigger('execute_' + options.run_scheduler_event)
  331. elif options.sync_all is not None:
  332. sync_all(options.force or 0)
  333. elif options.sync is not None:
  334. webnotes.reload_doc(options.sync[0], "doctype", options.sync[1])
  335. elif options.update:
  336. if not args:
  337. args = ["origin", conf.branch]
  338. update_erpnext(args[0], args[1])
  339. elif options.patch_sync_build:
  340. patch_sync_build()
  341. elif options.patch_sync:
  342. patch_sync()
  343. elif options.cleanup_data:
  344. from utilities import cleanup_data
  345. cleanup_data.run()
  346. elif options.domain:
  347. webnotes.conn.set_value('Website Settings', None, 'subdomain', options.domain)
  348. webnotes.conn.commit()
  349. print "Domain set to", options.domain
  350. elif options.clear_web:
  351. # build wn-web.js and wn-web.css
  352. from website.helpers.make_web_include_files import make
  353. make()
  354. import webnotes.webutils
  355. webnotes.webutils.clear_cache()
  356. elif options.clear_cache:
  357. clear_cache()
  358. elif options.clear_defaults:
  359. import webnotes.defaults
  360. webnotes.defaults.clear_cache()
  361. webnotes.clear_cache()
  362. elif options.append_future_import:
  363. append_future_import()
  364. elif options.backup:
  365. from webnotes.utils.backups import scheduled_backup
  366. scheduled_backup(ignore_files = True)
  367. # print messages
  368. if webnotes.message_log:
  369. print '\n'.join(webnotes.message_log)
  370. elif options.build_message_files:
  371. import webnotes.translate
  372. webnotes.translate.build_message_files()
  373. elif options.export_messages:
  374. import webnotes.translate
  375. webnotes.translate.export_messages(*options.export_messages)
  376. elif options.import_messages:
  377. import webnotes.translate
  378. webnotes.translate.import_messages(*options.import_messages)
  379. elif options.google_translate:
  380. from webnotes.translate import google_translate
  381. google_translate(*options.google_translate)
  382. elif options.translate:
  383. from webnotes.translate import translate
  384. translate(options.translate)
  385. elif options.docs:
  386. from core.doctype.documentation_tool.documentation_tool import write_static
  387. write_static()
  388. elif options.reset_perms:
  389. for d in webnotes.conn.sql_list("""select name from `tabDocType`
  390. where ifnull(istable, 0)=0 and ifnull(custom, 0)=0"""):
  391. try:
  392. webnotes.clear_cache(doctype=d)
  393. webnotes.reset_perms(d)
  394. except:
  395. pass
  396. if __name__=='__main__':
  397. run()