-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsane.py
1880 lines (1557 loc) · 70.1 KB
/
sane.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'''Sane, Makefile for humans.
Copyright Miguel Murça 2023
This work is licensed under the Creative Commons
Attribution-NonCommercial-ShareAlike 4.0 International License. To view a copy
of this license, visit http://creativecommons.org/licenses/by-nc-sa/4.0/.
'''
import os
import sys
import re
import inspect
import traceback
import builtins
import atexit
import textwrap
from concurrent.futures import ThreadPoolExecutor
from typing import Literal
from collections import namedtuple
__main__ = sys.modules['__main__']
class _Sane:
VERSION = '7.1'
ANSI = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
Context = namedtuple(
'Context', ('filename', 'lineno', 'code_context', 'index'))
Depends = namedtuple('Depends', ('value', 'context'))
Default = namedtuple('Default', ('func', 'context'))
singleton = None
@staticmethod
def strip_ansi(text):
return _Sane.ANSI.sub('', text)
@staticmethod
def get_context():
stack = inspect.stack(context=4)
for element in stack:
if element.frame.f_globals['__name__'] != __name__:
context = _Sane.Context(element.filename,
element.lineno,
element.code_context,
element.index)
stack.clear()
return context
@staticmethod
def get():
if _Sane.singleton is None:
_Sane.singleton = _Sane()
return _Sane.singleton
def __init__(self):
if _Sane.singleton is not None:
raise Exception()
self.initialize_properties()
self.setup_logging()
self.read_arguments()
self.run_on_exit()
def initialize_properties(self):
self.magic = False
self.finalized = False
self.default = None
self.cmds = {}
self.tasks = {}
self.tags = {}
self.operation = {}
self.incidence = {}
self.thread_exe = None
self.script_name = self.get_script_name()
def setup_logging(self):
self.verbose = False
if os.environ.get('NO_COLOR', False) or not sys.stdout.isatty():
self.color = False
else:
self.color = True
def get_script_name(self):
if hasattr(__main__, '__file__'):
return os.path.basename(__main__.__file__)
else:
return 'script'
def read_arguments(self):
args = sys.argv[1:]
if '--' in args:
cmd_arg_limit = args.index('--')
if cmd_arg_limit == len(args):
self.usage_error()
sane_args = list(args[:cmd_arg_limit])
cmd_args = tuple(args[cmd_arg_limit + 1:])
else:
sane_args = list(args)
cmd_args = None
color = self.get_cmdline_flag(sane_args, '-nc', '--no-color')
no_color = self.get_cmdline_flag(sane_args, '-c', '--color')
verbose = self.get_cmdline_flag(sane_args, '-v', '--verbose')
help_ = self.get_cmdline_flag(sane_args, '-h', '--help')
if color and no_color:
self.usage_error()
sys.exit(1)
if verbose:
self.verbose = True
if no_color:
self.color = False
if color:
self.color = True
if help_:
if verbose:
import pydoc
pydoc.pager(self.get_manual())
else:
print(self.get_long_usage())
self.finalized = True
sys.exit(0)
if '--list' in sane_args:
if cmd_args is not None or len(sane_args) != 1:
self.usage_error()
self.operation = {'mode': 'list'}
else:
self.setup_jobs(sane_args)
if len(sane_args) > 0:
if len(sane_args) > 1:
self.hint('Have you forgot a -- before the @cmd\'s arguments?\n')
self.usage_error()
cmd = sane_args.pop()
if cmd.startswith('-'):
self.usage_error()
else:
cmd = None
if cmd_args is None:
cmd_args = ()
self.operation = {
'mode': 'cmd',
'cmd': cmd,
'args': cmd_args,
}
def setup_jobs(self, args):
jobs = self.get_cmdline_value(args, '--jobs', '-j')
if jobs is not None:
try:
jobs = int(jobs)
if jobs == 1:
self.thread_exe = None
elif jobs == 0:
self.thread_exe = ThreadPoolExecutor(max_workers=None)
else:
self.thread_exe = ThreadPoolExecutor(max_workers=jobs)
except ValueError:
self.error('--jobs must be a number.')
self.usage_error()
def get_cmdline_flag(self, args, short, long_):
has_short = (short in args)
has_long = (long_ in args)
if has_short and has_long:
self.usage_error()
else:
is_set = False
if has_short:
args.remove(short)
is_set = True
elif has_long:
args.remove(long_)
is_set = True
return is_set
def get_cmdline_value(self, args, long_, short):
for i in range(len(args)):
arg = args[i]
has_long = arg.startswith(long_)
has_short = arg.startswith(short)
if has_long or has_short:
if has_short:
remaining = arg.removeprefix(short)
else:
remaining = arg.removeprefix(long_)
if remaining.startswith('='):
args.remove(arg)
return remaining.removeprefix('=')
elif len(remaining) == 0:
if i < len(args) - 1:
value = args[i+1]
args.remove(arg)
args.remove(value)
return value
def usage_error(self):
self.finalized = True
print(self.get_short_usage(), file=sys.stderr)
sys.exit(1)
def get_short_usage(self):
script = self.script_name
return (f'Usage: {script} [--no-color | --color] [--verbose] --help\n'
f' {script} --version\n'
f' {script} [--no-color | --color] --list\n'
f' {script} [--no-color | --color] [--verbose] [--jobs=<n>] [cmd] [-- ...args]')
def get_long_usage(self):
return ('Sane, Make for humans.\n'
f'{self.get_short_usage()}\n\n'
'Options:\n'
' --help Show this screen, or the manual if --verbose is set.\n'
' --version Print the current sane version.\n'
' --verbose Produce verbose output.\n'
' --color Enable ANSI color codes even in non-console terminals.\n'
' --no-color Disable ANSI color codes in the output.\n'
' --jobs=<n> Perform (at most) \'n\' tasks concurrently.\n'
' If suppressed, tasks are evaluated serially.\n'
' Passing \'0\' runs any number of tasks concurrently.'
'\n'
'Arguments given after \'--\' are passed to the provided @cmd.\n'
'If no command is given, the @default @cmd is ran, if it exists.')
def get_manual(self):
return inspect.cleandoc(f'''
# Sane, Make for humans.
(Hint: this manual is written in Markdown.
Use your favourite terminal markdown renderer for optimal results.)
## Index
* [What is sane?](#What-is-sane)
* [Quick start](#Quick-start)
* [Sane by example](#Sane-by-example)
* [The magic of sane, and what to do when it's corrupted](#The-magic-of-sane-and-what-to-do-when-its-corrupted)
* [Reference](#Reference)
- [@cmd](#cmd)
- [@task](#task)
- [@depends](#depends)
- [@tag](#tag)
* [Why use sane?](#Why-use-sane)
* [Hacking sane](#Hacking-sane)
* [Sane's license terms](#Sanes-license-terms)
* [TL;DR](#TLDR)
## What is sane?
Sane is a command runner. It defines a simple interface to declare
functions to run, and relationships between those functions. In
particular, it lets you define certain functions as requiring other
tasks to be completed first. This is not exactly the same as Make, which
operates based on files (and not commands), but the principles and goals
are very similar.
## Quick start
Place a copy of `sane.py` in a directory, and create a file to define
your tasks (I usually go with `make.py`). Then, simply `import sane`.
```python
# make.py
import sane
```
`make.py` now functions as an interactive script.
Call `python make.py --help` for more information, or keep on reading.
## Sane by example
(See also: [Reference](#Reference))
The author's favourite dessert, "camel slobber" ([really!][1]), is not
just extremely sweet, but very easy to prepare: you only need 6 eggs,
and a can of cooked condensed milk (which you might know as dulce de
leche). You'll want to beat the yolks together with the dulce de leche,
and fold that together with the whites beaten to a stiff peak. Then,
chill everything and serve.
We can write some Python to do that:
```python
# camel_slobber.py
def crack_eggs():
...
def beat_yolks():
...
def mix_yolks_and_dulce():
...
def beat_whites_to_stiff():
...
def fold():
...
def chill():
...
def serve():
...
```
Now, there are some clear dependencies between the functions above: you
can't beat the yolks before cracking the eggs, and you definitely can't
serve before folding the two mixes together. Sane allows you to express
these relationships.
We start by importing sane:
```python
# camel_slobber.py
import sane
def crack_eggs():
...
[...]
```
This will automatically transform the `camel_slobber.py` file into an
interactive script; try it out:
```terminal
$ python cammel_slobber.py
[error] No @cmd given, and no @default @cmd exists.
(Add @default to a @cmd to run it when no @cmd is specified.)
(If you need help getting started with sane, run 'man.py --verbose --help)'.
```
Sane is telling us we need a @default @cmd. @cmds are tasks that we
expect the user to want to execute directly, and that can (therefore)
take some arguments. You declare a function to be a @cmd by decorating
it accordingly:
```python
# camel_slobber.py
import sane
[...]
@sane.default
@sane.cmd
def serve():
print("Oooh, ahhh!")
```
Naturally, the @default @cmd is the one that's ran if no @cmd is
specified by the user. If we now run the script again...
```terminal
$ python camel_slobber.py
Ooooh, ahhh!
```
Sane executed our @default @cmd! Let's define an alternative @cmd:
```python
[...]
@sane.cmd
def save_for_later():
print("Self control really pays off sometimes!")
```
To run `save_for_later`, we just...
```terminal
$ python camel_slobber.py save_for_later
Self control really pays off sometimes!
```
As mentioned already, @cmds also admit arguments; let's introduce yet
another @cmd, which takes a couple of arguments:
```python
# camel_slobber.py
[...]
@sane.cmd
def pay_compliments(first, second):
print(f"This camel slobber isn't just {{first}}, it's also {{second}}!")
```
Let's try to pay a compliment to the chef:
```terminal
$ python camel_slobber.py pay_compliments "very sweet"
Have you forgot a -- before the @cmd's arguments?
Usage: man.py [--no-color | --color] [--verbose] --help
man.py --version
man.py [--no-color | --color] --list
man.py [--no-color | --color] [--verbose] [--jobs=<n>] [cmd] [-- ...args]
```
Ah, yes, I seem to be missing a "--" to separate the arguments meant for
sane from the arguments meant for my @cmd. Let me try this again:
```terminal
$ python camel_slobber.py pay_compliments -- "very sweet"
[error] Wrong number of arguments for pay_compliments(first, second).
[... a snippet of the pay_compliments code ...]
```
Oh, now I'm missing a second argument, as I'd specified in the function
definition. Third time's the charm:
```terminal
$ python camel_slobber.py pay_compliments -- "very sweet" "extremely tasty"
This camel slobber isn't just very sweet, it's also extremely tasty!
```
That looks like correct output to me! Do note that arguments given from
the command line will always be passed to the @cmds as strings.
Now let's backtrack a little, and focus on the preparation of the camel
slobber. We have a few @tasks to accomplish before being able to
`serve()` the dessert; but, in principle, there's no reasons the user
would want to invoke these @tasks directly. Therefore, we decorate these
functions accordingly:
```python
@sane.task
def crack_eggs():
...
@sane.task
def beat_yolks():
...
@sane.task
def mix_yolks_and_dulce():
...
@sane.task
def beat_whites_to_stiff():
...
[...]
```
Note that @tasks don't take any arguments; sane won't let you decorate
a function taking arguments with @task. @tasks aren't very interesting
by themselves; their point is to be called upon as dependencies.
The recipe we have states the following dependencies:
```plain
[crack_eggs] ─┬───> [beat_yolks] ───>[mix_yolks_and_dulce]─┬──>[fold]───>[chill]───>[serve]
│ │
└─────> [beat_whites_to_stiff] ──────────────┘
```
(Notice how, if you have help, you can take care of the yolks and whites
at the same time; sane is aware of this, and can take advantage of it.
See the `--verbose --help` for the `--jobs` flag.)
We can express these dependencies by use of the @depends decorator:
```python
@sane.task
def crack_eggs():
...
@sane.task
@sane.depends(on_task=crack_eggs)
def beat_yolks():
...
@sane.task
@sane.depends(on_task=beat_yolks)
def mix_yolks_and_dulce():
...
@sane.task
@sane.depends(on_task=crack_eggs)
def beat_whites_to_stiff():
...
@sane.task
@sane.depends(on_task=mix_yolks_and_dulce)
@sane.depends(on_task=beat_whites_to_stiff)
def fold():
...
@sane.task
@sane.depends(on_task=fold)
def chill():
...
@sane.cmd
@sane.depends(on_task=chill)
def serve():
...
```
Now, whenever we want to serve some camel slobber, sane will take care
of preparing everything else. We can ask sane to report on what it's
doing by passing the `--verbose` flag:
```terminal
$ python camel_slobber.py --verbose serve
[log] Running crack_eggs()
...
[log] Running beat_yolks()
...
[log] Running beat_whites_to_stiff()
...
[log] Running mix_yolks_and_dulce()
...
[log] Running fold()
...
[log] Running chill()
...
[log] Running serve()
```
In this case, sane decided to beat the yolks before beating the whites
to a stiff, but it could just as well have decided the other way round,
since there's no relationship between the two tasks.
Note also that, just like we can define dependencies on @tasks, we can
also define dependencies on @cmds, with the difference that we must also
specify the corresponding arguments, in that case. This means that two
dependencies on the same @cmd with different arguments are considered
two different dependencies. So, for example, we could add...
```python
@sane.cmd
@sane.depends(on_cmd=serve, args=())
def eat():
...
```
Finally, let's talk about @tag. Because sane is very flexible, you can
create multiple @tasks on the fly, which is often useful for real-world
uses. For example, and moving beyond the camel slobber example, if
you're writing a compilation/linking file, you might have something as
follows:
```python
def make_compile_task(file):
@sane.task
def compile_():
...
for file in source_files:
make_compile_task(file)
```
(**NB:** Because of a quirk of for loops in Python, the use of a
`make_compile_task` is **necessary**. Otherwise, all tasks will refer
to the same `file` in `source_files`, namely, the last `file` in the
collection. This is because `file` is, in some sense, always the same
variable, just taking the different values in `source_files`. Whenever
the different @tasks are finally ran, they will all compile this same
`file`.)
Then, a `link` @task depends on every compilation @task. But how can we
define this dependency? If we try something like...
```python
# This won't work!
@sane.cmd
@sane.depends(on_task=compile_)
def link():
...
```
...then Python will complain about namespaces, because `compile_` is
defined in a different scope. This may also happen if you define recipes
out of order (relative to the dependencies relationships), so sane lets
you reference other functions by name:
```python
# This won't work either!
@sane.cmd
@sane.depends(on_task='compile_')
def link():
...
```
This produces a different error message, now coming from sane:
```terminal
[error] There's more than one @task named compile_.
...
@sane.cmd
> @sane.depends(on_task='compile_')
def link():
(You can reference a function directly, instead of a string.)
(Alternatively, use @tag, and @depends(on_tag=...).)
```
Obviously, every compilation task we've defined (one for each source
file) has the same name, "compile_", and because sane can't tell whether
you mean to define a dependency on every such function or only a
particular one, it cannot proceed.
To deal with this situation, sane also has the concept of @tags. You can
tag any @task with one or more strings of your choosing, and define
dependencies on a @tag. If a @task depends on a @tag, it means it
depends on every @task with that @tag.
So, in the present example, we would define the linking-compilation
dependency as follows:
```python
# This will work!
def make_compile_task(file):
@sane.task
@sane.tag('compilation')
def compile_():
...
for file in source_files:
make_compile_task(file)
@sane.cmd
@sane.depends(on_tag='compilation')
def link():
...
```
## The magic of sane, and what to do when it's corrupted
> **TL;DR:** Getting weird results or unexpected behaviour from your
> sane code? Just call `if __name__ == '__main__': sane.sane()` at the
> end of your file.
Sane uses the `atexit` module to magically execute the @cmds and @tasks
after they've all been defined. At the time of writing, the official
Python documentation does not specify any limitation to the sort of code
that can (or even should!) be ran inside an `atexit` handler. But, this
doesn't mean that there's no difference between the `atexit` context,
and the usual script context: in fact, the sane code responsible for
understanding dependencies and running the relevant tasks runs after the
Python interpreter has begun to shut down. This has several
consequences: for example, the definition of `__main__` will be
different by the time your functions run, and some things are simply
(undocumentedly) not allowed, like spawning new jobs with the
`concurrent.futures` module. This is not a problem if all you're doing
is reading and writing to some files and spawning external commands.
But -- especially when using external modules, which might make
assumptions about the sort of environment they're being used in -- it
*may* be a problem.
So, sane lets you opt out of this magic functionality, by letting you
run the relevant sane bootstrapping code yourself at the end of the
main file. You can do this with
```python
[... definitions of @tasks and @cmds, and other contents ...]
if __name__ == '__main__':
sane.sane()
```
## Reference
### @cmd
{self.cmd_decorator.__doc__.strip()}
### @task
{self.task_decorator.__doc__.strip()}
### @depends
{self.depends_decorator.__doc__.strip()}
### @tag
{self.tag_decorator.__doc__.strip()}
## Why use sane?
Sane is 1. extremely portable, and 2. low (mental) overhead. This is
because (1.) sane is fully contained in a single Python file, so you can
(and should!) distribute it alongside your codebase, and (2.) sane
is vanilla Python. The second property makes sane extremely expressive
-- in fact, sane can do anything Python can -- and prevents the
introduction of more domain-specific languages.
Of course, with great power comes great responsibility, and sane is
trivially Turing complete; that is, after all, the point. Therefore,
there are more (and more unpredictable) ways to fail critically. But,
as Python has shown over the years, this flexibility is not much of a
problem in practice, especially when compared to the advantages it
brings, and given that other, more structured, tools are still
available to be used in tandem.
Regardless, sane thoroughly attempts to validate the input program, and
will always try to guide you to write a correct program.
## Hacking sane
This section is written for those who either want to
* modify sane's internals,
* better understand how sane works, or
* are writing sufficiently non-standard Python that sane's inner
workings become relevant.
Of course, this requires examining sane's source code, which is
available and was written to be as much self-documenting as possible;
the present text is only accompaniment. It's also expected that you
understand how Python decorators work, and relevant standard library
package documentation should also be considered, where applicable.
Sane operates on the basis of a singleton, defined in the module as
`sane._sane`. This singleton is an instantiation of the `sane._Sane`
class, where all the relevant sane code is defined.
All of the user-facing decorators (i.e., @cmd, @task, @depends, @tag)
are exposed to the user by reexporting these symbols from the singleton
(see also [Python's documentation regarding import rules][2]).
Given this, sane operates in, essentially, two stages: the first stage
concerns registration of user definitions and validation of user
arguments, as well as augmenting the given objects with the metadata
that sane will need in the second stage. In the second stage, sane
performs any necessary resolution (in particular, and for example,
matching `str` arguments to the functions they refer to; see @depends),
parses command-line arguments, and, if applicable, topologically sorts
dependencies and dispatches execution of the relevant @cmds and @tasks.
The first stage is a product of the normal execution of the script;
the singleton is instantiated by means of the `import sane` statement,
and the code inside each of decorators handles argument validation and
metadata registration as appropriate. This does imply some limitations,
as decorators are evaluated "as they appear". This means that, for
example, a @depends decorator cannot validate at its evaluation time
whether a dependency given by name (`str`) is valid or not, as it may
happen that the corresponding definition appears later in the file, and
so has not yet been recorded. Thus, the second stage.
The second stage corresponds to the `_sane.main` function, and is also
exposed to the user (cf. the
[magic section](#The-magic-of-sane-and-what-to-do-when-its-corrupted)).
By default, sane runs in "magic mode", wherein the second stage is
registered as an [atexit][3] callback. Ensuring that this code only runs
when the script has successfully terminated requires monkey patching the
possible exit functions (namely, `sys.exit` and `builtins.exit`). Cf.
the relevant code for details. In any case, the code guards against
running more than once (and so can be prevented from running at all by
manipulation of the singleton's state).
Finally, note that whenever an object is augmented with sane-relevant
metadata, this metadata is stored in a `dict` attribute named
`__sane__`. Inspection of this dictionary at different points of
execution may help with understanding sane's operation.
## Sane's license terms
Sane is distributed under a [CC-BY-NC-SA-4.0][4] license. *Informally*,
this means you are free to use sane in a non-commercial context (i.e.,
personally and academically), as well as modify sane, as long as you:
- Give proper credit and provide a link to the license (so, don't
modify sane's __doc__ string at the top of the file),
- Indicate if and what changes were made,
- Share your modifications of sane under this same license.
For uses of sane under different terms, please contact the author.
If you use do use sane under the CC-BY-NC-SA-4.0 terms, the author adds
a (non-legally enforceable) clause that they would be very thankful if
you would [buy them a coffee][5].
## TL;DR
1. Import sane.
2. Use @sane.cmd for anything you'd want to run from the command line,
and @sane.task for anything you need to get done.
3. Decorate @cmds and @tasks with @depends, as appropriate.
4. Use @tag if you want to depend on a family of @tasks.
5. run `python your_script.py [sane args] -- [your args]`.
## Links
[1]: https://en.m.wikipedia.org/wiki/Baba_de_camelo
[2]: https://docs.python.org/3/reference/simple_stmts.html#import
[3]: https://docs.python.org/3/library/atexit.html
[4]: http://creativecommons.org/licenses/by-nc-sa/4.0/.
[5]: https://www.paypal.me/miguelmurca/4.00
''')
def cmd_decorator(self, *args, **kwargs):
"""Defines this function as a sane @cmd.
Example use:
```
@sane.cmd
def my_cmd():
\"\"\"Description of this command.\"\"\"
pass
```
A @cmd is a function that the user can invoke from the command line, and
generally corresponds to some end-goal.
A @cmd is allowed to have arguments, but only positional arguments, and
not keyword arguments. The reasoning is that, since @cmds are allowed to
be invoked from the command line, keyword arguments cannot be reliably
specified.
For this same reason, when a @cmd is evoked from the command line, the
arguments given are passed as strings to the function.
Finally, for the same reason, two @cmds cannot have the same name.
Therefore, any two functions with @cmd decorators must have different
`__name__` attributes.
When a @cmd is evoked from within other @cmds or @tasks, the dependency
tree is first ran (see also @depends and @task).
The user can list all defined @cmds by calling the main script with the
`--list` flag. If the `--verbose` flag is also given, the `__doc__`
string of the function and arguments are also listed.
"""
context = _Sane.get_context()
if self.finalized:
self.error('@cmd cannot appear after sane().')
self.show_context(context, 'error')
self.hint('(Move sane() to the end of the file.)')
if len(args) > 1 or len(kwargs) > 0:
self.error('@cmd does not take arguments.')
self.show_context(context, 'error')
self.hint('(To specify other properties, use @tag or @depends.)')
sys.exit(1)
elif len(args) == 0:
self.error('@cmd does not have parentheses.')
self.show_context(context, 'error')
self.hint('(Remove the parentheses.)')
sys.exit(1)
func = args[0]
if not hasattr(func, '__call__'):
self.error('@cmd must decorate a function.')
self.show_context(context, 'error')
sys.exit(1)
self.ensure_positional_args_only(context, func)
self.ensure_no_tags(func, context)
if not hasattr(func, '__name__'):
self.error('A @cmd must have a name.')
self.show_context(context, 'error')
self.hint('(Use a @task instead.)')
sys.exit(1)
if func.__name__ in self.cmds:
other_, other_context = self.cmds[func.__name__]
self.error('@cmd names must be unique.')
self.show_context(context, 'error')
self.show_context(other_context, 'hint')
self.hint('(Use a @task instead.)')
sys.exit(1)
props = self.get_props(func)
if self.is_task_or_cmd(func):
self.error('More than one @cmd or @task.')
self.show_context(context, 'error')
self.hint(
'(A function can only have a single @cmd or @task decorator.)')
sys.exit(1)
props['type'] = 'cmd'
props['context'] = context
def cmd(*args, **kwargs):
if not self.finalized:
context = _Sane.get_context()
self.warn('Calling a @cmd from outside other '
'@cmds or @tasks ignores @depends.')
self.show_context(context, 'warn')
return func(*args)
else:
return self.run_tree(func, args)
cmd.__dict__['__sane__'] = {'type': 'wrapper', 'inner': func}
self.cmds[func.__name__] = func
return cmd
def task_decorator(self, *args, **kwargs):
"""Defines this function as a sane @task.
Example use:
```
@sane.task
def my_task():
pass
```
A @task is a function that sane can call as part of its execution, and
that may require the execution of other @tasks or @cmds. It generally
corresponds to a modular step in a process, but that is not expected to
be the final step.
A @task is not allowed to have arguments (see, instead, @cmd). Likewise,
@tasks cannot be called upon by the user, and are not listed when the
user executes the main script with `--list`.
@tasks may share the same `__name__` attributes (cf. with @cmd).
In this case, however, they may only serve as dependencies by means of
the @tag decorator.
"""
context = _Sane.get_context()
if self.finalized:
self.error('@task cannot appear after sane().')
self.show_context(context)
self.hint('(Move sane() to the end of the file.)')
if len(args) > 1 or len(kwargs) > 0:
self.error('@task does not take arguments.')
self.show_context(context, 'error')
self.hint('(To specify other properties, use @tag or @depends.)')
sys.exit(1)
elif len(args) == 0:
self.error('@task does not have parentheses.')
self.show_context(context, 'error')
self.hint('(Remove the parentheses.)')
sys.exit(1)
func = args[0]
if not hasattr(func, '__call__'):
self.error('@task must decorate a function.')
self.show_context(context, 'error')
sys.exit(1)
self.ensure_no_args(func, context)
props = self.get_props(func)
if self.is_task_or_cmd(func):
self.error('More than one @cmd or @task.')
self.show_context(context, 'error')
self.hint(
'(A function can only have a single @cmd or @task decorator.)')
sys.exit(1)
props['type'] = 'task'
props['context'] = context
def task():
if not self.finalized:
context = _Sane.get_context()
self.warn('Calling a @task from outside other '
'@cmds or @tasks ignores @depends.')
self.show_context(context, 'warn')
return func()
else:
return self.run_tree(func, ())
task.__dict__['__sane__'] = {'type': 'wrapper', 'inner': func}
self.tasks.setdefault(func.__name__, []).append(func)
return task
def depends_decorator(self, *pargs, **args):
"""Defines a dependency between this sane @cmd or @task and another sane function.
Example use:
```
@sane.task
def a_task():
pass
@sane.cmd
@sane.depends(on_task=a_task)