選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 
 
 

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