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.
 
 
 
 
 
 

486 lines
14 KiB

  1. #!/usr/bin/env python
  2. # Copyright 2013 Web Notes Technologies Pvt Ltd
  3. # License: MIT. 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.utils import bundlejs
  53. bundlejs.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. patch_sync_build()
  64. def patch_sync_build():
  65. patch_sync()
  66. rebuild()
  67. def patch_sync():
  68. apply_latest_patches()
  69. import webnotes.modules.patch_handler
  70. for l in webnotes.modules.patch_handler.log_list:
  71. if "failed: STOPPED" in l:
  72. return
  73. sync_all()
  74. clear_cache()
  75. def clear_cache():
  76. import webnotes.sessions
  77. webnotes.sessions.clear_cache()
  78. def append_future_import():
  79. """appends from __future__ import unicode_literals to py files if necessary"""
  80. import os
  81. import conf
  82. conf_path = os.path.abspath(conf.__file__)
  83. if conf_path.endswith("pyc"):
  84. conf_path = conf_path[:-1]
  85. base_path = os.path.dirname(conf_path)
  86. for path, folders, files in os.walk(base_path):
  87. for f in files:
  88. if f.endswith('.py'):
  89. file_path = os.path.join(path, f)
  90. with open(file_path, 'r') as pyfile:
  91. content = pyfile.read()
  92. future_import = 'from __future__ import unicode_literals'
  93. if future_import in content: continue
  94. content = content.split('\n')
  95. idx = -1
  96. for c in content:
  97. idx += 1
  98. if c and not c.startswith('#'):
  99. break
  100. content.insert(idx, future_import)
  101. content = "\n".join(content)
  102. with open(file_path, 'w') as pyfile:
  103. pyfile.write(content)
  104. def setup_options():
  105. from optparse import OptionParser
  106. parser = OptionParser()
  107. # install
  108. parser.add_option('--install', nargs=2, metavar = "NEW_DB_NAME SOURCE_PATH",
  109. help="install db")
  110. parser.add_option('--install_fresh', nargs=1, metavar = "NEW_DB_NAME",
  111. help="install fresh db")
  112. # update
  113. parser.add_option("--update", help="Pull, run latest patches and sync all",
  114. nargs=2, metavar="ORIGIN BRANCH")
  115. parser.add_option("--backup", help="Takes backup of database in backup folder",
  116. default=False, action="store_true")
  117. # build
  118. parser.add_option("-b", "--build", default=False, action="store_true",
  119. help="minify + concat js files")
  120. parser.add_option("-w", "--watch", default=False, action="store_true",
  121. help="watch and minify + concat js files, if necessary")
  122. parser.add_option("--no_cms", default=False, action="store_true",
  123. help="do not build wn-web.js and wn-css.js")
  124. parser.add_option("-d", "--db",
  125. dest="db_name",
  126. help="Apply the patches on given db")
  127. parser.add_option("--password",
  128. help="Password for given db", nargs=1)
  129. parser.add_option("--clear_web", default=False, action="store_true",
  130. help="clear web cache")
  131. parser.add_option("--clear_cache", default=False, action="store_true",
  132. help="clear cache")
  133. parser.add_option("--domain", metavar="DOMAIN",
  134. help="store domain in Website Settings", nargs=1)
  135. # git
  136. parser.add_option("--status", default=False, action="store_true",
  137. help="git status")
  138. parser.add_option("--git", nargs=1, default=False,
  139. metavar = "git options",
  140. help="run git with options in both repos")
  141. parser.add_option("--pull", nargs=2, default=False,
  142. metavar = "remote branch",
  143. help="git pull (both repos)")
  144. parser.add_option("--commit", nargs=1, default=False,
  145. metavar = "commit both repos",
  146. help="git commit -a -m [comment]")
  147. parser.add_option("--push", nargs=2, default=False,
  148. metavar = "remote branch",
  149. help="git push (both repos) [remote] [branch]")
  150. parser.add_option("--checkout", nargs=1, default=False,
  151. metavar = "branch",
  152. help="git checkout [branch]")
  153. parser.add_option("-l", "--latest",
  154. action="store_true", dest="run_latest", default=False,
  155. help="Apply the latest patches")
  156. # patch
  157. parser.add_option("-p", "--patch", nargs=1, dest="patch_list", metavar='patch_module',
  158. action="append",
  159. help="Apply patch")
  160. parser.add_option("-f", "--force",
  161. action="store_true", dest="force", default=False,
  162. help="Force Apply all patches specified using option -p or --patch")
  163. parser.add_option('--reload_doc', nargs=3, metavar = "module doctype docname",
  164. help="reload doc")
  165. parser.add_option('--export_doc', nargs=2, metavar = "doctype docname",
  166. help="export doc")
  167. # diff
  168. parser.add_option('--diff_ref_file', nargs=0, \
  169. help="Get missing database records and mismatch properties, with file as reference")
  170. parser.add_option('--diff_ref_db', nargs=0, \
  171. help="Get missing .txt files and mismatch properties, with database as reference")
  172. # scheduler
  173. parser.add_option('--run_scheduler', default=False, action="store_true",
  174. help="Trigger scheduler")
  175. parser.add_option('--run_scheduler_event', nargs=1, metavar="[all|daily|weekly|monthly]",
  176. help="Run scheduler event")
  177. # misc
  178. parser.add_option("--replace", nargs=3, default=False,
  179. metavar = "search replace_by extension",
  180. help="file search-replace")
  181. parser.add_option("--sync_all", help="Synchronize all DocTypes using txt files",
  182. nargs=0)
  183. parser.add_option("--sync", help="Synchronize given DocType using txt file",
  184. nargs=2, metavar="module doctype (use their folder names)")
  185. parser.add_option("--patch_sync_build", action="store_true", default=False,
  186. help="run latest patches, sync all and rebuild js css")
  187. parser.add_option("--patch_sync", action="store_true", default=False,
  188. help="run latest patches, sync all")
  189. parser.add_option("--cleanup_data", help="Cleanup test data", default=False,
  190. action="store_true")
  191. parser.add_option("--append_future_import", default=False, action="store_true",
  192. help="append from __future__ import unicode literals to py files")
  193. parser.add_option("--test", help="Run test", metavar="MODULE",
  194. nargs=1)
  195. parser.add_option("--build_message_files", default=False, action="store_true",
  196. help="Build message files for translation")
  197. parser.add_option('--export_messages', nargs=2, metavar="LANG FILENAME",
  198. help="""Export all messages for a language to translation in a csv file.
  199. Example, lib/wnf.py --export_messages hi hindi.csv""")
  200. parser.add_option('--import_messages', nargs=2, metavar="LANG FILENAME",
  201. help="""Import messages for a language and make language files.
  202. Example, lib/wnf.py --export_messages hi hindi.csv""")
  203. parser.add_option('--google_translate', nargs=3, metavar="LANG INFILE OUTFILE",
  204. help="""Auto translate using Google Translate API""")
  205. parser.add_option('--translate', nargs=1, metavar="LANG",
  206. help="""Rebuild translation for the given langauge and
  207. use Google Translate to tranlate untranslated messages""")
  208. return parser.parse_args()
  209. def run():
  210. sys.path.append('.')
  211. sys.path.append('lib')
  212. sys.path.append('app')
  213. (options, args) = setup_options()
  214. # build
  215. if options.build:
  216. from webnotes.utils import bundlejs
  217. if options.no_cms:
  218. cms_make = False
  219. else:
  220. cms_make = True
  221. bundlejs.bundle(False, cms_make)
  222. return
  223. elif options.watch:
  224. from webnotes.utils import bundlejs
  225. bundlejs.watch(True)
  226. return
  227. # code replace
  228. elif options.replace:
  229. print options.replace
  230. replace_code('.', options.replace[0], options.replace[1], options.replace[2], force=options.force)
  231. return
  232. # git
  233. elif options.status:
  234. os.chdir('lib')
  235. os.system('git status')
  236. os.chdir('../app')
  237. os.system('git status')
  238. return
  239. elif options.git:
  240. os.chdir('lib')
  241. os.system('git %s' % options.git)
  242. os.chdir('../app')
  243. os.system('git %s' % options.git)
  244. return
  245. import webnotes
  246. import conf
  247. from webnotes.db import Database
  248. import webnotes.modules.patch_handler
  249. # connect
  250. if options.db_name is not None:
  251. if options.password:
  252. webnotes.connect(options.db_name, options.password)
  253. else:
  254. webnotes.connect(options.db_name)
  255. elif not any([options.install, options.pull, options.install_fresh]):
  256. webnotes.connect(conf.db_name)
  257. if options.pull:
  258. pull(options.pull[0], options.pull[1], build=True)
  259. elif options.commit:
  260. os.chdir('lib')
  261. os.system('git commit -a -m "%s"' % (options.commit))
  262. os.chdir('../app')
  263. os.system('git commit -a -m "%s"' % (options.commit))
  264. elif options.push:
  265. os.chdir('lib')
  266. os.system('git push %s %s' % (options.push[0], options.push[1]))
  267. os.chdir('../app')
  268. os.system('git push %s %s' % (options.push[0], options.push[1]))
  269. elif options.checkout:
  270. os.chdir('lib')
  271. os.system('git checkout %s' % options.checkout)
  272. os.chdir('../app')
  273. os.system('git checkout %s' % options.checkout)
  274. # patch
  275. elif options.patch_list:
  276. # clear log
  277. webnotes.modules.patch_handler.log_list = []
  278. # run individual patches
  279. for patch in options.patch_list:
  280. webnotes.modules.patch_handler.run_single(\
  281. patchmodule = patch, force = options.force)
  282. print '\n'.join(webnotes.modules.patch_handler.log_list)
  283. # reload
  284. elif options.reload_doc:
  285. webnotes.modules.patch_handler.reload_doc(\
  286. {"module":options.reload_doc[0], "dt":options.reload_doc[1], "dn":options.reload_doc[2]})
  287. print '\n'.join(webnotes.modules.patch_handler.log_list)
  288. elif options.export_doc:
  289. from webnotes.modules import export_doc
  290. export_doc(options.export_doc[0], options.export_doc[1])
  291. # run all pending
  292. elif options.run_latest:
  293. apply_latest_patches()
  294. elif options.install:
  295. from webnotes.install_lib.install import Installer
  296. inst = Installer('root')
  297. inst.import_from_db(options.install[0], source_path=options.install[1],
  298. verbose = 1)
  299. elif options.install_fresh:
  300. from webnotes.install_lib.install import Installer
  301. inst = Installer('root')
  302. inst.import_from_db(options.install_fresh, source_path="lib/conf/Framework.sql",
  303. verbose = 1)
  304. elif options.diff_ref_file is not None:
  305. import webnotes.modules.diff
  306. webnotes.modules.diff.diff_ref_file()
  307. elif options.diff_ref_db is not None:
  308. import webnotes.modules.diff
  309. webnotes.modules.diff.diff_ref_db()
  310. elif options.run_scheduler:
  311. import webnotes.utils.scheduler
  312. print webnotes.utils.scheduler.execute()
  313. elif options.run_scheduler_event is not None:
  314. import webnotes.utils.scheduler
  315. print webnotes.utils.scheduler.trigger('execute_' + options.run_scheduler_event)
  316. elif options.sync_all is not None:
  317. sync_all(options.force or 0)
  318. elif options.sync is not None:
  319. import webnotes.model.sync
  320. webnotes.model.sync.sync(options.sync[0], options.sync[1], options.force or 0)
  321. elif options.update:
  322. update_erpnext(options.update[0], options.update[1])
  323. elif options.patch_sync_build:
  324. patch_sync_build()
  325. elif options.patch_sync:
  326. patch_sync()
  327. elif options.cleanup_data:
  328. from utilities import cleanup_data
  329. cleanup_data.run()
  330. elif options.domain:
  331. webnotes.conn.set_value('Website Settings', None, 'subdomain', options.domain)
  332. webnotes.conn.commit()
  333. print "Domain set to", options.domain
  334. elif options.clear_web:
  335. # build wn-web.js and wn-web.css
  336. from website.helpers.make_web_include_files import make
  337. make()
  338. import website.utils
  339. website.utils.clear_cache()
  340. elif options.clear_cache:
  341. clear_cache()
  342. elif options.append_future_import:
  343. append_future_import()
  344. elif options.backup:
  345. from webnotes.utils.backups import scheduled_backup
  346. scheduled_backup()
  347. # print messages
  348. if webnotes.message_log:
  349. print '\n'.join(webnotes.message_log)
  350. if options.test is not None:
  351. module_name = options.test
  352. import unittest
  353. del sys.argv[1:]
  354. # is there a better way?
  355. exec ('from %s import *' % module_name) in globals()
  356. unittest.main()
  357. elif options.build_message_files:
  358. import webnotes.translate
  359. webnotes.translate.build_message_files()
  360. elif options.export_messages:
  361. import webnotes.translate
  362. webnotes.translate.export_messages(*options.export_messages)
  363. elif options.import_messages:
  364. import webnotes.translate
  365. webnotes.translate.import_messages(*options.import_messages)
  366. elif options.google_translate:
  367. from webnotes.translate import google_translate
  368. google_translate(*options.google_translate)
  369. elif options.translate:
  370. from webnotes.translate import build_message_files, \
  371. export_messages, google_translate, import_messages
  372. print "Extracting messages..."
  373. build_message_files()
  374. print "Compiling messages in one file..."
  375. export_messages(options.translate, '_lang_tmp.csv')
  376. print "Translating via Google Translate..."
  377. google_translate(options.translate, '_lang_tmp.csv', '_lang_tmp1.csv')
  378. print "Updating language files..."
  379. import_messages(options.translate, '_lang_tmp1.csv')
  380. print "Deleting temp files..."
  381. os.remove('_lang_tmp.csv')
  382. os.remove('_lang_tmp1.csv')
  383. if __name__=='__main__':
  384. run()