1"""
2Deployment file to facilitate AbiPy releases.
3Use invoke --list to get list of tasks
4"""
5
6import os
7
8from invoke import task
9from monty.os import cd
10
11#from abipy.core.release import __version__ as CURRENT_VER
12#NEW_VER = datetime.datetime.today().strftime("%Y.%-m.%-d")
13
14ABIPY_ROOTDIR = os.path.dirname(__file__)
15DOCS_DIR = os.path.join(ABIPY_ROOTDIR, "docs")
16
17
18@task
19def make_doc(ctx):
20    with cd(DOCS_DIR):
21        ctx.run("make clean")
22        ctx.run("make", env=dict(READTHEDOCS="1"), pty=True)
23        open_doc(ctx)
24
25
26@task
27def push_doc(ctx):
28    make_doc(ctx)
29    with cd(DOCS_DIR):
30        ctx.run("./ghp_import.py _build/html/ -n -p")
31
32
33@task
34def open_doc(ctx):
35    import webbrowser
36    webbrowser.open_new_tab("file://" + os.path.join(ABIPY_ROOTDIR, "docs/_build/html/index.html"))
37
38
39@task
40def twine(ctx):
41    with cd(ABIPY_ROOTDIR):
42        ctx.run("rm dist/*.*", warn=True)
43        ctx.run("python setup.py register sdist bdist_wheel")
44        ctx.run("twine upload dist/*")
45
46
47@task
48def pytest(ctx):
49    pytest_cmd = r"""\
50pytest -n 2 --cov-config=.coveragerc --cov=abipy -v --doctest-modules abipy \
51    --ignore=abipy/integration_tests --ignore=abipy/data/refs --ignore=abipy/scripts/ \
52    --ignore=abipy/examples/plot --ignore=abipy/examples/flows --ignore=abipy/gui
53"""
54    with cd(ABIPY_ROOTDIR):
55        ctx.run(pytest_cmd, pty=True)
56
57
58@task
59def style(ctx):
60    with cd(ABIPY_ROOTDIR):
61        ctx.run("pycodestyle 2>&1 | tee style.log", pty=True)
62        ctx.run("flake8 --count --show-source --statistics | tee -a style.log", pty=True)
63        #ctx.run("pydocstyle abipy | tee -a style.log", pty=True)
64
65
66@task
67def plots(ctx):
68    with cd(os.path.join(ABIPY_ROOTDIR, "abipy", "examples")):
69        ctx.run("_runplots.py", pty=True)
70
71
72@task
73def flows(ctx):
74    with cd(os.path.join(ABIPY_ROOTDIR, "abipy", "examples")):
75        ctx.run("_runflows.py", pty=True)
76
77
78@task
79def pygrep(ctx, pattern):
80    """
81    Grep for `pattern` in all py files contained in
82    """
83    # grep -r -i --include \*.h
84    # Syntax notes:
85    #    -r - search recursively
86    #    -i - case-insensitive search
87    #    --include=\*.${file_extension} - search files that match the extension(s) or file pattern only
88    with cd(os.path.join(ABIPY_ROOTDIR, "abipy",)):
89        cmd = 'grep -r -i --color --include "*.py" "%s" .' % pattern
90        print("Executing:", cmd)
91        ctx.run(cmd, pty=True)
92
93#@task
94#def move_to_master(ctx):
95#    ctx.run("git tag -a v%s -m \"v%s release\"" % (NEW_VER, NEW_VER))
96#    ctx.run("git push --tags")
97#    ctx.run("git checkout master")
98#    ctx.run("git pull")
99#    ctx.run("git merge develop")
100#    ctx.run("git push")
101#    ctx.run("git checkout develop")
102
103
104#@task
105#def update_changelog(ctx):
106#
107#    output = subprocess.check_output(["git", "log", "--pretty=format:%s",
108#                                      "v%s..HEAD" % CURRENT_VER])
109#    lines = ["* " + l for l in output.decode("utf-8").strip().split("\n")]
110#    with open("CHANGES.rst") as f:
111#        contents = f.read()
112#    l = "=========="
113#    toks = contents.split(l)
114#    head = "\n\nv%s\n" % NEW_VER + "-" * (len(NEW_VER) + 1) + "\n"
115#    toks.insert(-1, head + "\n".join(lines))
116#    with open("CHANGES.rst", "w") as f:
117#        f.write(toks[0] + l + "".join(toks[1:]))
118
119
120#@task
121#def release(ctx, run_tests=True):
122#    ctx.run("rm -r dist build abipy.egg-info", warn=True)
123#    set_ver(ctx)
124#    if run_tests: pytest(ctx)
125#    publish(ctx)
126#    log_ver(ctx)
127#    update_doc(ctx)
128#    merge_stable(ctx)
129#    release_github(ctx)
130
131
132#@task
133#def watchdog(ctx, jobs="auto", sleep_time=5):
134#    """
135#    Start watchdog service to watch F90 files and execute `make` when changes are detected.
136#    """
137#    from monty.termcolor import cprint
138#    cprint("Starting watchdog service to watch F90 files and execute `make` when changes are detected", "green")
139#    cprint("Enter <CTRL + C> in the terminal to kill the service.", "green")
140#
141#    cprint(f"Start watching py files with sleep_time {sleep_time} s ....", "green")
142#    top = find_top_build_tree(".", with_abinit=True)
143#    jobs = max(1, number_of_cpus() // 2) if jobs == "auto" else int(jobs)
144#
145#    # http://thepythoncorner.com/dev/how-to-create-a-watchdog-in-python-to-look-for-filesystem-changes/
146#    # https://stackoverflow.com/questions/19991033/generating-multiple-observers-with-python-watchdog
147#    import time
148#    from watchdog.observers import Observer
149#    from watchdog.events import PatternMatchingEventHandler
150#    event_handler = PatternMatchingEventHandler(patterns="*.py", ignore_patterns="",
151#                                                   ignore_directories=False, case_sensitive=True)
152#
153#    def on_created(event):
154#        print(f"hey, {event.src_path} has been created!")
155#
156#    def on_deleted(event):
157#        print(f"what the f**k! Someone deleted {event.src_path}!")
158#
159#    def on_modified(event):
160#        print(f"hey buddy, {event.src_path} has been modified")
161#        cmd = "abicheck.py"
162#        cprint("Executing: %s" % cmd, "yellow")
163#        with cd(top):
164#            try:
165#                result = ctx.run(cmd, pty=True)
166#                if result.ok:
167#                    cprint("Command completed successfully", "green")
168#                    cprint("Watching for changes ...", "green")
169#            except Exception:
170#                cprint(f"Command returned non-zero exit status", "red")
171#                cprint(f"Keep on watching for changes hoping you get it right ...", "red")
172#
173#    def on_moved(event):
174#        print(f"ok ok ok, someone moved {event.src_path} to {event.dest_path}")
175#
176#    event_handler.on_created = on_created
177#    event_handler.on_deleted = on_deleted
178#    event_handler.on_modified = on_modified
179#    event_handler.on_moved = on_moved
180#
181#    path = ABIPY_ROOTDIR
182#
183#    observer = Observer()
184#    observer.schedule(event_handler, path, recursive=True)
185#    observer.start()
186#
187#    try:
188#        while True:
189#            time.sleep(sleep_time)
190#    except KeyboardInterrupt:
191#        observer.stop()
192#        observer.join()
193