Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 
 
 

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