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.
 
 
 
 
 
 

512 rivejä
15 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. 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. # update
  114. parser.add_option("--update", help="Pull, run latest patches and sync all",
  115. nargs=2, metavar="ORIGIN BRANCH")
  116. parser.add_option("--backup", help="Takes backup of database in backup folder",
  117. default=False, action="store_true")
  118. # build
  119. parser.add_option("-b", "--build", default=False, action="store_true",
  120. help="minify + concat js files")
  121. parser.add_option("-w", "--watch", default=False, action="store_true",
  122. help="watch and minify + concat js files, if necessary")
  123. parser.add_option("--no_cms", default=False, action="store_true",
  124. help="do not build wn-web.js and wn-css.js")
  125. parser.add_option("-d", "--db",
  126. dest="db_name",
  127. help="Apply the patches on given db")
  128. parser.add_option("--password",
  129. help="Password for given db", nargs=1)
  130. parser.add_option("--clear_web", default=False, action="store_true",
  131. help="clear web cache")
  132. parser.add_option("--clear_cache", default=False, action="store_true",
  133. help="clear cache")
  134. parser.add_option("--clear_defaults", default=False, action="store_true",
  135. help="clear cache of defaults")
  136. parser.add_option("--domain", metavar="DOMAIN",
  137. help="store domain in Website Settings", nargs=1)
  138. # git
  139. parser.add_option("--status", default=False, action="store_true",
  140. help="git status")
  141. parser.add_option("--git", nargs=1, default=False,
  142. metavar = "git options",
  143. help="run git with options in both repos")
  144. parser.add_option("--pull", nargs=2, default=False,
  145. metavar = "remote branch",
  146. help="git pull (both repos)")
  147. parser.add_option("--commit", nargs=1, default=False,
  148. metavar = "commit both repos",
  149. help="git commit -a -m [comment]")
  150. parser.add_option("--push", nargs=2, default=False,
  151. metavar = "remote branch",
  152. help="git push (both repos) [remote] [branch]")
  153. parser.add_option("--checkout", nargs=1, default=False,
  154. metavar = "branch",
  155. help="git checkout [branch]")
  156. parser.add_option("-l", "--latest",
  157. action="store_true", dest="run_latest", default=False,
  158. help="Apply the latest patches")
  159. # patch
  160. parser.add_option("-p", "--patch", nargs=1, dest="patch_list", metavar='patch_module',
  161. action="append",
  162. help="Apply patch")
  163. parser.add_option("-f", "--force",
  164. action="store_true", dest="force", default=False,
  165. help="Force Apply all patches specified using option -p or --patch")
  166. parser.add_option('--reload_doc', nargs=3, metavar = "module doctype docname",
  167. help="reload doc")
  168. parser.add_option('--export_doc', nargs=2, metavar = "doctype docname",
  169. help="export doc")
  170. # diff
  171. parser.add_option('--diff_ref_file', nargs=0, \
  172. help="Get missing database records and mismatch properties, with file as reference")
  173. parser.add_option('--diff_ref_db', nargs=0, \
  174. help="Get missing .txt files and mismatch properties, with database as reference")
  175. # scheduler
  176. parser.add_option('--run_scheduler', default=False, action="store_true",
  177. help="Trigger scheduler")
  178. parser.add_option('--run_scheduler_event', nargs=1, metavar="[all|daily|weekly|monthly]",
  179. help="Run scheduler event")
  180. # misc
  181. parser.add_option("--replace", nargs=3, default=False,
  182. metavar = "search replace_by extension",
  183. help="file search-replace")
  184. parser.add_option("--sync_all", help="Synchronize all DocTypes using txt files",
  185. nargs=0)
  186. parser.add_option("--sync", help="Synchronize given DocType using txt file",
  187. nargs=2, metavar="module doctype (use their folder names)")
  188. parser.add_option("--patch_sync_build", action="store_true", default=False,
  189. help="run latest patches, sync all and rebuild js css")
  190. parser.add_option("--patch_sync", action="store_true", default=False,
  191. help="run latest patches, sync all")
  192. parser.add_option("--cleanup_data", help="Cleanup test data", default=False,
  193. action="store_true")
  194. parser.add_option("--append_future_import", default=False, action="store_true",
  195. help="append from __future__ import unicode literals to py files")
  196. parser.add_option("--test", help="Run test", metavar="MODULE",
  197. nargs=1)
  198. parser.add_option("--build_message_files", default=False, action="store_true",
  199. help="Build message files for translation")
  200. parser.add_option('--export_messages', nargs=2, metavar="LANG FILENAME",
  201. help="""Export all messages for a language to translation in a csv file.
  202. Example, lib/wnf.py --export_messages hi hindi.csv""")
  203. parser.add_option('--import_messages', nargs=2, metavar="LANG FILENAME",
  204. help="""Import messages for a language and make language files.
  205. Example, lib/wnf.py --import_messages hi hindi.csv""")
  206. parser.add_option('--google_translate', nargs=3, metavar="LANG INFILE OUTFILE",
  207. help="""Auto translate using Google Translate API""")
  208. parser.add_option('--translate', nargs=1, metavar="LANG",
  209. help="""Rebuild translation for the given langauge and
  210. use Google Translate to tranlate untranslated messages. use "all" """)
  211. parser.add_option("--reset_perms", default=False, action="store_true",
  212. help="Reset permissions for all doctypes.")
  213. return parser.parse_args()
  214. def run():
  215. sys.path.append('.')
  216. sys.path.append('lib')
  217. sys.path.append('app')
  218. (options, args) = setup_options()
  219. # build
  220. if options.build:
  221. from webnotes.utils import bundlejs
  222. if options.no_cms:
  223. cms_make = False
  224. else:
  225. cms_make = True
  226. bundlejs.bundle(False, cms_make)
  227. return
  228. elif options.watch:
  229. from webnotes.utils import bundlejs
  230. bundlejs.watch(True)
  231. return
  232. # code replace
  233. elif options.replace:
  234. print options.replace
  235. replace_code('.', options.replace[0], options.replace[1], options.replace[2], force=options.force)
  236. return
  237. # git
  238. elif options.status:
  239. os.chdir('lib')
  240. os.system('git status')
  241. os.chdir('../app')
  242. os.system('git status')
  243. return
  244. elif options.git:
  245. os.chdir('lib')
  246. os.system('git %s' % options.git)
  247. os.chdir('../app')
  248. os.system('git %s' % options.git)
  249. return
  250. import webnotes
  251. import conf
  252. from webnotes.db import Database
  253. import webnotes.modules.patch_handler
  254. # connect
  255. if options.db_name is not None:
  256. if options.password:
  257. webnotes.connect(options.db_name, options.password)
  258. else:
  259. webnotes.connect(options.db_name)
  260. elif not any([options.install, options.pull, options.install_fresh]):
  261. webnotes.connect(conf.db_name)
  262. if options.pull:
  263. pull(options.pull[0], options.pull[1], build=True)
  264. elif options.commit:
  265. os.chdir('lib')
  266. os.system('git commit -a -m "%s"' % (options.commit))
  267. os.chdir('../app')
  268. os.system('git commit -a -m "%s"' % (options.commit))
  269. elif options.push:
  270. os.chdir('lib')
  271. os.system('git push %s %s' % (options.push[0], options.push[1]))
  272. os.chdir('../app')
  273. os.system('git push %s %s' % (options.push[0], options.push[1]))
  274. elif options.checkout:
  275. os.chdir('lib')
  276. os.system('git checkout %s' % options.checkout)
  277. os.chdir('../app')
  278. os.system('git checkout %s' % options.checkout)
  279. # patch
  280. elif options.patch_list:
  281. # clear log
  282. webnotes.modules.patch_handler.log_list = []
  283. # run individual patches
  284. for patch in options.patch_list:
  285. webnotes.modules.patch_handler.run_single(\
  286. patchmodule = patch, force = options.force)
  287. print '\n'.join(webnotes.modules.patch_handler.log_list)
  288. # reload
  289. elif options.reload_doc:
  290. webnotes.modules.patch_handler.reload_doc(\
  291. {"module":options.reload_doc[0], "dt":options.reload_doc[1], "dn":options.reload_doc[2]})
  292. print '\n'.join(webnotes.modules.patch_handler.log_list)
  293. elif options.export_doc:
  294. from webnotes.modules import export_doc
  295. export_doc(options.export_doc[0], options.export_doc[1])
  296. # run all pending
  297. elif options.run_latest:
  298. apply_latest_patches()
  299. elif options.install:
  300. from webnotes.install_lib.install import Installer
  301. inst = Installer('root')
  302. inst.import_from_db(options.install[0], source_path=options.install[1],
  303. verbose = 1)
  304. elif options.install_fresh:
  305. from webnotes.install_lib.install import Installer
  306. inst = Installer('root')
  307. inst.import_from_db(options.install_fresh, source_path="lib/conf/Framework.sql",
  308. verbose = 1)
  309. elif options.diff_ref_file is not None:
  310. import webnotes.modules.diff
  311. webnotes.modules.diff.diff_ref_file()
  312. elif options.diff_ref_db is not None:
  313. import webnotes.modules.diff
  314. webnotes.modules.diff.diff_ref_db()
  315. elif options.run_scheduler:
  316. import webnotes.utils.scheduler
  317. print webnotes.utils.scheduler.execute()
  318. elif options.run_scheduler_event is not None:
  319. import webnotes.utils.scheduler
  320. print webnotes.utils.scheduler.trigger('execute_' + options.run_scheduler_event)
  321. elif options.sync_all is not None:
  322. sync_all(options.force or 0)
  323. elif options.sync is not None:
  324. webnotes.reload_doc(options.sync[0], "doctype", options.sync[1])
  325. elif options.update:
  326. update_erpnext(options.update[0], options.update[1])
  327. elif options.patch_sync_build:
  328. patch_sync_build()
  329. elif options.patch_sync:
  330. patch_sync()
  331. elif options.cleanup_data:
  332. from utilities import cleanup_data
  333. cleanup_data.run()
  334. elif options.domain:
  335. webnotes.conn.set_value('Website Settings', None, 'subdomain', options.domain)
  336. webnotes.conn.commit()
  337. print "Domain set to", options.domain
  338. elif options.clear_web:
  339. # build wn-web.js and wn-web.css
  340. from website.helpers.make_web_include_files import make
  341. make()
  342. import webnotes.webutils
  343. webnotes.webutils.clear_cache()
  344. elif options.clear_cache:
  345. clear_cache()
  346. elif options.clear_defaults:
  347. import webnotes.defaults
  348. webnotes.defaults.clear_cache()
  349. webnotes.clear_cache()
  350. elif options.append_future_import:
  351. append_future_import()
  352. elif options.backup:
  353. from webnotes.utils.backups import scheduled_backup
  354. scheduled_backup(ignore_files = True)
  355. # print messages
  356. if webnotes.message_log:
  357. print '\n'.join(webnotes.message_log)
  358. if options.test is not None:
  359. module_name = options.test
  360. import unittest
  361. del sys.argv[1:]
  362. # is there a better way?
  363. exec ('from %s import *' % module_name) in globals()
  364. unittest.main()
  365. elif options.build_message_files:
  366. import webnotes.translate
  367. webnotes.translate.build_message_files()
  368. elif options.export_messages:
  369. import webnotes.translate
  370. webnotes.translate.export_messages(*options.export_messages)
  371. elif options.import_messages:
  372. import webnotes.translate
  373. webnotes.translate.import_messages(*options.import_messages)
  374. elif options.google_translate:
  375. from webnotes.translate import google_translate
  376. google_translate(*options.google_translate)
  377. elif options.translate:
  378. from webnotes.translate import build_message_files, \
  379. export_messages, google_translate, import_messages
  380. languages = [options.translate]
  381. if options.translate=="all":
  382. from startup import lang_list
  383. languages = lang_list
  384. print "Extracting messages..."
  385. build_message_files()
  386. for lang in languages:
  387. if lang != "en":
  388. filename = 'app/translations/'+lang+'.csv'
  389. print "For " + lang + ":"
  390. print "Compiling messages in one file..."
  391. export_messages(lang, '_lang_tmp.csv')
  392. print "Translating via Google Translate..."
  393. google_translate(lang, '_lang_tmp.csv', filename)
  394. print "Updating language files..."
  395. import_messages(lang, filename)
  396. print "Deleting temp files..."
  397. os.remove('_lang_tmp.csv')
  398. elif options.reset_perms:
  399. for d in webnotes.conn.sql_list("""select name from `tabDocType`
  400. where ifnull(istable, 0)=0 and ifnull(custom, 0)=0"""):
  401. webnotes.reset_perms(d)
  402. webnotes.clear_cache(doctype=d)
  403. if __name__=='__main__':
  404. run()