-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpuppet-ts-mode.el
1516 lines (1318 loc) · 60.3 KB
/
puppet-ts-mode.el
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
;;; puppet-ts-mode.el --- Major mode for Puppet using Tree-sitter -*- lexical-binding: t; -*-
;; Copyright (c) 2024, 2025 Stefan Möding
;; Author: Stefan Möding <[email protected]>
;; Maintainer: Stefan Möding <[email protected]>
;; Version: 0.1.0
;; Created: <2024-03-02 13:05:03 stm>
;; Updated: <2025-01-07 17:16:18 stm>
;; URL: https://github.com/smoeding/puppet-ts-mode
;; Keywords: languages
;; Package-Requires: ((emacs "29.1"))
;; This file is NOT part of GNU Emacs.
;; This program is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; For a full copy of the GNU General Public License
;; see <http://www.gnu.org/licenses/>.
;; This file incorporates work covered by the following copyright and
;; permission notice:
;; Copyright (C) 2013-2014, 2016 Sebastian Wiesner <[email protected]>
;; Copyright (C) 2013, 2014 Bozhidar Batsov <[email protected]>
;; Copyright (C) 2011 Puppet Labs Inc
;;; Commentary:
;; This package uses a Tree-sitter parser to provide syntax highlighting,
;; indentation, alignment, completion, xref navigation and code checking
;; for the Puppet domain-specific language.
;;
;; Syntax highlighting: Fontification is supported using custom faces for
;; Puppet syntax elements like comments, strings, variables, constants,
;; keywords, resource types and their metaparameters. Syntax errors can be
;; shown using a warning face by setting `treesit-font-lock-level' to 4.
;;
;; Indentation: Automatic indentation according to the Puppet coding
;; standards is provided.
;;
;; Alignment: Alignment rules for common Puppet expressions are included.
;; The function `puppet-ts-align-block' (bound to "C-c C-a") aligns the
;; current block with respect to "=>" for attributes and hashes or "=" for
;; parameter lists. The fat arrow and equal sign are electric and they
;; perform automatic alignment. Electricity is controlled by
;; `puppet-ts-greater-is-electric' and `puppet-ts-equal-is-electric'.
;;
;; Completion: The mode updates the `completion-at-point' component to
;; complete variable names, resource types and resource parameters.
;; Tree-sitter is used to extract the local variable names from the
;; current buffer.
;;
;; Imenu: Navigation to the resource types and variable assignments used in
;; a file is implemented using the imenu facility.
;;
;; Cross-reference navigation: When point is on an identifier for a class,
;; defined type, data type or custom function, the definition of that
;; element can easily be opened with `xref-find-definitions' (bound to
;; "M-."). The list of directories that will be searched to locate the
;; definition is customized in `puppet-ts-module-path'.
;;
;; Code checking: Validate the syntax of the current buffer with
;; `puppet-ts-validate' (bound to "C-c C-v"). Lint the current buffer for
;; semantic errors with `puppet-ts-lint' (bound to "C-c C-l"). Apply the
;; current buffer in noop-mode with `puppet-ts-apply' (bound to "C-c C-c").
;;
;; The package uses a Tree-sitter library to parse Puppet code and you need
;; to install the appropriate parser. This can be done by using this Elisp
;; code:
;;
;; (require 'puppet-ts-mode)
;; (puppet-ts-mode-install-grammar)
;;
;; Note that a C compiler is required for this step. Using the function
;; provided by the package ensures that a version of the parser matching the
;; package will be installed. These commands should also be used to update
;; the parser to the correct version when the package is updated.
;;
;;; Code:
;;; Requirements
(require 'treesit)
(require 'thingatpt)
(require 'align)
(require 'xref)
(require 'seq)
(eval-when-compile
(require 'cl-lib)
(require 'skeleton)
(require 'rx))
;;; Customization
(defgroup puppet-ts nil
"Write Puppet manifests in Emacs."
:prefix "puppet-ts-"
:group 'languages
:link '(url-link :tag "Repository" "https://github.com/smoeding/puppet-ts-mode"))
(defvar puppet-ts--file-attribute-constants
'("file" "directory" "link")
"Attributes for file resources that will be formatted as constants.")
(defvar puppet-ts--package-attribute-constants
'("present" "absent" "installed" "latest")
"Attributes for package resources that will be formatted as constants.")
(defvar puppet-ts--service-attribute-constants
'("running" "stopped")
"Attributes for service resources that will be formatted as constants.")
;; https://www.puppet.com/docs/puppet/latest/metaparameter.html
(defvar puppet-ts--metaparameters
'("alias" "audit" "before" "consume" "export" "loglevel" "noop"
"notify" "require" "schedule" "stage" "subscribe" "tag" "ensure")
"Metaparameter attributes for all resource types.
Strictly speakting, \"ensure\" is not a real metaparameter, but it
is added here because it is common and important.")
;; https://www.puppet.com/docs/puppet/latest/function.html
(defvar puppet-ts--builtin-functions
'("abs" "alert" "all" "annotate" "any" "assert_type" "binary_file"
"break" "call" "camelcase" "capitalize" "ceiling" "chomp" "chop"
"compare" "convert_to" "create_resources" "defined" "dig" "digest"
"downcase" "each" "emerg" "empty" "epp" "eyaml_lookup_key" "file"
"filter" "find_file" "find_template" "flatten" "floor" "fqdn_rand"
"generate" "get" "getvar" "group_by" "hiera" "hiera_array"
"hiera_hash" "hiera_include" "hocon_data" "import" "index"
"inline_epp" "inline_template" "join" "json_data" "keys" "length"
"lest" "lookup" "lstrip" "map" "match" "max" "md5" "min"
"module_directory" "new" "next" "partition" "realize" "reduce"
"regsubst" "return" "reverse_each" "round" "rstrip" "scanf" "sha1"
"sha256" "shellquote" "size" "slice" "sort" "split" "sprintf"
"step" "strftime" "strip" "tagged" "template" "then" "tree_each"
"type" "unique" "unwrap" "upcase" "values" "versioncmp" "with"
"yaml_data"
;; Bolt: https://puppet.com/docs/bolt/0.x/plan_functions.html
"apply" "apply_prep" "add_facts" "facts" "fail_plan" "file_upload"
"get_targets" "puppetdb_fact" "puppetdb_query" "run_command"
"run_plan" "run_script" "run_task" "set_feature" "set_var" "vars"
"without_default_logging")
"Internal functions provided by Puppet.")
(defvar puppet-ts--statement-functions
'("include" "require" "contain" "tag" ; Catalog statements
"debug" "info" "notice" "warning" "err" "crit" ; Logging statements
"fail") ; Failure statements
"Statement functions provided by Puppet.")
(defcustom puppet-ts-greater-is-electric t
"Non-nil (and non-null) means a fat arrow should be electric.
Inserting the fat arrow \"=>\" in a hash or an attribute list
will perform automatic alignment if electric."
:type 'boolean
:group 'puppet-ts)
(defcustom puppet-ts-equal-is-electric t
"Non-nil (and non-null) means an equal sign should be electric.
Inserting an equal sign \"=\" in a parameter list will perform
automatic alignment if electric."
:type 'boolean
:group 'puppet-ts)
;; Regular expressions
(defvar puppet-ts--constants-regex
(rx-to-string `(seq bos
,(cons 'or (append puppet-ts--service-attribute-constants
puppet-ts--package-attribute-constants
puppet-ts--file-attribute-constants))
eos)
'no-group)
"Regex to match Puppet attributes.")
(defvar puppet-ts--metaparameters-regex
(rx-to-string `(seq bos
,(cons 'or puppet-ts--metaparameters)
eos)
'no-group)
"Regex to match Puppet metaparameters.")
(defvar puppet-ts--builtin-functions-regex
(rx-to-string `(seq bos
,(cons 'or (append puppet-ts--builtin-functions
puppet-ts--statement-functions))
eos)
'no-group)
"Regex to match Puppet internal functions.")
(defvar puppet-ts--statement-functions-regex
(rx-to-string `(seq bos
,(cons 'or puppet-ts--statement-functions)
eos)
'no-group)
"Regex to match Puppet statement functions.")
;;; Faces
(defface puppet-ts-comment
'((t :inherit font-lock-comment-face))
"Face for comments in Puppet."
:group 'puppet-ts)
(defface puppet-ts-string
'((t :inherit font-lock-string-face))
"Face for strings in Puppet."
:group 'puppet-ts)
(defface puppet-ts-regexp
'((t :inherit font-lock-regexp-face))
"Face for regular expressions."
:group 'puppet-ts)
(defface puppet-ts-escape
'((t :inherit font-lock-escape-face))
"Face for escape sequences."
:group 'puppet-ts)
(defface puppet-ts-keyword
'((t :inherit font-lock-keyword-face))
"Face for keywords in Puppet."
:group 'puppet-ts)
(defface puppet-ts-resource-type
'((t :inherit font-lock-type-face))
"Face for resource types in Puppet."
:group 'puppet-ts)
(defface puppet-ts-builtin
'((t :inherit font-lock-builtin-face))
"Face for built-in functions in Puppet."
:group 'puppet-ts)
(defface puppet-ts-constant
'((t :inherit font-lock-constant-face))
"Face for a constant in Puppet."
:group 'puppet-ts)
(defface puppet-ts-variable-name
'((t :inherit font-lock-variable-name-face))
"Face for the name of a variable in Puppet."
:group 'puppet-ts)
(defface puppet-ts-variable-use
'((t :inherit font-lock-variable-use-face))
"Face for the name of a variable being referenced in Puppet."
:group 'puppet-ts)
(defface puppet-ts-function-name
'((t :inherit font-lock-function-name-face))
"Face for the name of a function in Puppet."
:group 'puppet-ts)
(defface puppet-ts-function-call
'((t :inherit font-lock-function-call-face))
"Face for the name of a function being called in Puppet."
:group 'puppet-ts)
(defface puppet-ts-operator
'((t :inherit font-lock-operator-face))
"Face for operators."
:group 'puppet-ts)
(defface puppet-ts-negation-char
'((t :inherit font-lock-negation-char-face))
"Face for negation characters."
:group 'puppet-ts)
(defface puppet-ts-number
'((t :inherit font-lock-number-face))
"Face for numbers."
:group 'puppet-ts)
(defface puppet-ts-warning
'((t :inherit font-lock-warning-face))
"Face for language errors found by the parser."
:group 'puppet-ts)
;; Font-Lock
(defvar puppet-ts-mode-feature-list
;; Level 1 usually contains only comments and definitions.
;; Level 2 usually adds keywords, strings, data types, etc.
;; Level 3 usually represents full-blown fontifications, including
;; assignments, constants, numbers and literals, etc.
;; Level 4 adds everything else that can be fontified: delimiters,
;; operators, brackets, punctuation, all functions, properties,
;; variables, etc.
'((comment definition)
(keyword string regexp resource-type)
(constant number variable string-interpolation escape-sequence builtin function)
(operator error))
"`treesit-font-lock-feature-list' for `puppet-ts-mode'.")
(defvar puppet-ts-mode-font-lock-settings
`( ;;
:feature comment
:language puppet
((comment) @puppet-ts-comment)
:feature string
:language puppet
(((double_quoted_string) @puppet-ts-string)
((single_quoted_string) @puppet-ts-string)
((heredoc) @puppet-ts-string))
:feature regexp
:language puppet
((regex) @puppet-ts-regexp)
:feature string-interpolation
:language puppet
:override t
((interpolation) @puppet-ts-variable-use)
:feature escape-sequence
:language puppet
:override t
((double_quoted_string (escape_sequence) @puppet-ts-escape)
(single_quoted_string (escape_sequence) @puppet-ts-escape)
(heredoc (escape_sequence) @puppet-ts-escape))
:feature variable
:language puppet
((statement :anchor (variable ["$" (name)] @puppet-ts-variable-name))
(variable ["$" (name)] @puppet-ts-variable-use))
:feature constant
:language puppet
(([(true) (false) (default) (undef)] @puppet-ts-constant))
:feature number
:language puppet
((number) @puppet-ts-number)
:feature definition
:language puppet
((class_definition ["class" "inherits"] @puppet-ts-keyword)
(define_definition "define" @puppet-ts-keyword)
(node_definition "node" @puppet-ts-keyword)
(plan_definition "plan" @puppet-ts-keyword)
(type_alias "type" @puppet-ts-keyword)
;; function definitions
(function_definition "function" @puppet-ts-keyword)
(function_definition (classname (name) @puppet-ts-function-name))
;; names of defined classes, defined types, nodes, ...
(classname (name) @puppet-ts-resource-type)
;; hostnames in a node definition
(hostname (dotted_name) @puppet-ts-resource-type))
:feature builtin
:language puppet
((statement_function (name) @puppet-ts-builtin
(:match ,puppet-ts--statement-functions-regex
@puppet-ts-builtin))
(function_call (name) @puppet-ts-builtin
(:match ,puppet-ts--builtin-functions-regex
@puppet-ts-builtin))
(named_access (name) @puppet-ts-builtin
(:match ,puppet-ts--builtin-functions-regex
@puppet-ts-builtin))
(attribute name: (name) @puppet-ts-builtin
(:match ,puppet-ts--metaparameters-regex
@puppet-ts-builtin))
(attribute value: (name) @puppet-ts-builtin
(:match ,puppet-ts--constants-regex
@puppet-ts-builtin)))
:feature function
:language puppet
((function_call (name) @puppet-ts-function-call))
:feature keyword
:language puppet
(((if "if" @puppet-ts-keyword))
((elsif "elsif" @puppet-ts-keyword))
((else "else" @puppet-ts-keyword))
((unless "unless" @puppet-ts-keyword))
((case "case" @puppet-ts-keyword))
(binary operator: ["and" "or" "in"] @puppet-ts-keyword))
:feature resource-type
:language puppet
(((resource_type [(name) (virtual) (exported)] @puppet-ts-resource-type))
;; arguments to statement functions
((statement_function
(argument_list (argument (name) @puppet-ts-resource-type))))
;; data and resource reference types
((type) @puppet-ts-resource-type))
:feature operator
:language puppet
((unary operator: "!" @puppet-ts-negation-char)
(unary operator: _ @puppet-ts-operator)
(binary operator: _ @puppet-ts-operator))
:feature error
:language puppet
:override t
((ERROR) @puppet-ts-warning))
"`treesit-font-lock-settings' for `puppet-ts-mode'.")
;; Indentation
(defcustom puppet-ts-indent-level 2
"Number of spaces for each indententation step."
:group 'puppet-ts
:type 'integer
:safe 'integerp)
(defcustom puppet-ts-indent-tabs-mode nil
"Indentation can insert tabs in puppet mode if this is non-nil."
:group 'puppet-ts
:type 'boolean
:safe 'booleanp)
(defvar puppet-ts-indent-rules
`((puppet
;; top-level statements start in column zero
((parent-is "manifest") column-0 0)
;; blocks
((node-is ")") parent-bol 0)
((node-is "]") parent-bol 0)
((node-is "}") parent-bol 0)
((parent-is "block") parent-bol puppet-ts-indent-level)
;; compound statements
((node-is "elsif") parent-bol 0)
((node-is "else") parent-bol 0)
;; additional statements
((parent-is "case") parent-bol puppet-ts-indent-level)
((parent-is "selector") parent-bol puppet-ts-indent-level)
;; arrays & hashes
((parent-is "array") parent-bol puppet-ts-indent-level)
((parent-is "hash") parent-bol puppet-ts-indent-level)
;; resources & attributes
((match "attribute" "attribute_list" nil 2 nil) first-sibling 0)
((parent-is "resource_body") parent-bol puppet-ts-indent-level)
((parent-is "resource_type") parent-bol puppet-ts-indent-level)
((parent-is "resource_reference") parent-bol puppet-ts-indent-level)
((parent-is "resource_collector") parent-bol puppet-ts-indent-level)
;; class/defined type parameters
((parent-is "parameter_list") parent-bol puppet-ts-indent-level)
;; function calls
((match "argument" "argument_list" nil 2 nil) first-sibling 0)
((parent-is "function_call") parent-bol puppet-ts-indent-level)
;; default
(catch-all parent-bol 0)))
"Indentation rules for `puppet-ts-mode'.")
;; Helper macros & functions
(defmacro puppet-ts-node-type-predicate (&rest type)
"Return a lambda function to test if a node has type TYPE.
The macro can take more than one argument in which case the node
type must match one of the given type names."
`(lambda (node)
(string-match-p (rx bos (or ,@type) eos) (treesit-node-type node))))
(defsubst puppet-ts--parent-resource-type (node)
"Return the resource type that NODE belongs to."
(treesit-parent-until node
(puppet-ts-node-type-predicate "resource_type")
t))
(defun puppet-ts-resource-type (node)
"Return the resource type that NODE belongs to."
(if-let* ((resource (puppet-ts--parent-resource-type node))
(name (treesit-search-subtree resource "\\`name\\'")))
(treesit-node-text name t)))
(defun puppet-ts-resource-title (node)
"Return the title of the resource type that NODE belongs to."
(if-let* ((resource (puppet-ts--parent-resource-type node))
(body (treesit-search-subtree resource "\\`resource_body\\'"))
(title (treesit-search-subtree body "\\`resource_title\\'")))
(treesit-node-text title t)))
(defun puppet-ts-hierarchy (node)
"Return a list of the node hierarchy for NODE."
(cl-loop for n = node
then (treesit-node-parent n)
until (treesit-node-eq n (treesit-buffer-root-node))
if (treesit-node-check n 'named)
collect (treesit-node-type n)))
;; Imenu
(defun puppet-ts--resource-imenu-name (node)
"Return the imenu title for NODE."
(let ((type (treesit-node-type node)))
(cond ((string-equal type "resource_type")
(concat (puppet-ts-resource-type node)
" "
(puppet-ts-resource-title node)))
((string-equal type "statement")
(let ((lhs (treesit-node-child node 0 t)))
(if (and lhs (string-equal (treesit-node-type lhs) "variable"))
(treesit-node-text lhs t)))))))
(defun puppet-ts--variable-assignment-p (node)
"Return t if NODE is an assignment to a variable."
(if (string-equal (treesit-node-type node) "statement")
(let ((lhs (treesit-node-child node 0 t)))
(and lhs (string-equal (treesit-node-type lhs) "variable")))))
(defvar puppet-ts-simple-imenu-settings
'((nil "resource_type" nil puppet-ts--resource-imenu-name)
("Variables" "statement"
puppet-ts--variable-assignment-p puppet-ts--resource-imenu-name))
"The simple Imenu settings for `puppet-ts-mode'.
It should be a list of (CATEGORY REGEXP PRED NAME-FN).")
;;; Checking
(defcustom puppet-ts-validate-command "puppet parser validate --color=false"
"Command to validate the syntax of a Puppet manifest."
:type 'string
:group 'puppet-ts)
(defcustom puppet-ts-lint-command
(concat
"puppet-lint --with-context "
"--log-format \"%{path}:%{line}: %{kind}: %{message} (%{check})\"")
"Command to lint a Puppet manifest."
:type 'string
:group 'puppet-ts)
(defcustom puppet-ts-apply-command "puppet apply --verbose --noop"
"Command to apply a Puppet manifest."
:type 'string
:group 'puppet-ts)
(defvar-local puppet-ts-last-validate-command nil
"The last command used for validation.")
(defvar-local puppet-ts-last-lint-command nil
"The last command used for linting.")
(defvar-local puppet-ts-last-apply-command nil
"The last command used to apply a manifest.")
(defun puppet-ts-run-check-command (command buffer-name-template)
"Run COMMAND to check the current buffer.
BUFFER-NAME-TEMPLATE is used to create the buffer name."
(save-some-buffers (not compilation-ask-about-save) nil)
(compilation-start command nil (lambda (_)
(format buffer-name-template command))))
(defun puppet-ts-read-command (prompt previous-command default-command)
"Read a command from minibuffer with PROMPT.
PREVIOUS-COMMAND or DEFAULT-COMMAND are used if set."
(let* ((buffer-file-name (or (buffer-file-name) ""))
(filename (or (file-remote-p buffer-file-name 'localname)
buffer-file-name)))
(read-string prompt (or previous-command
(concat default-command " "
(shell-quote-argument filename))))))
(defun puppet-ts-validate (command)
"Validate the syntax of the current buffer with COMMAND.
When called interactively, prompt for COMMAND."
(interactive (list (puppet-ts-read-command "Validate command: "
puppet-ts-last-validate-command
puppet-ts-validate-command)))
(setq puppet-ts-last-validate-command command)
(puppet-ts-run-check-command command "*Puppet Validate: %s*"))
(defun puppet-ts-lint (command)
"Lint the current buffer with COMMAND.
When called interactively, prompt for COMMAND."
(interactive (list (puppet-ts-read-command "Lint command: "
puppet-ts-last-lint-command
puppet-ts-lint-command)))
(setq puppet-ts-last-lint-command command)
(puppet-ts-run-check-command command "*Puppet Lint: %s*"))
(defun puppet-ts-apply (command)
"Apply the current manifest with COMMAND.
When called interactively, prompt for COMMAND."
(interactive (list (puppet-ts-read-command "Apply command: "
puppet-ts-last-apply-command
puppet-ts-apply-command)))
(setq puppet-ts-last-apply-command command)
(puppet-ts-run-check-command command "*Puppet Apply: %s*"))
;; Alignment
(add-to-list 'align-sq-string-modes 'puppet-ts-mode)
(add-to-list 'align-dq-string-modes 'puppet-ts-mode)
(add-to-list 'align-open-comment-modes 'puppet-ts-mode)
(defconst puppet-ts-mode-align-rules
'((puppet-resource-arrow
(regexp . "\\(\\s-*\\)[=+]>\\(\\s-*\\)")
(group . (1 2))
(modes . '(puppet-ts-mode))
(separate . entire))
(puppet-param-default
(regexp . "\\(\\s-+\\)$[a-z_][a-zA-Z0-9_]*\\(\\s-*\\)=\\(\\s-*\\)")
(group . (1 2 3))
(modes . '(puppet-ts-mode)))
(puppet-param-nodefault
(regexp . "\\(\\s-+\\)$[a-z_][a-zA-Z0-9_]*")
(modes . '(puppet-ts-mode))))
"Align rules for Puppet attributes and parameters.")
(defconst puppet-ts-mode-align-exclude-rules
'((puppet-nested
(regexp . "\\s-*=>\\s-*\\({[^}]*}\\)")
(modes . '(puppet-ts-mode))
(separate . entire))
(puppet-comment
(regexp . "^\\s-*#\\(.*\\)")
(modes . '(puppet-ts-mode))))
"Rules for excluding lines from alignment for Puppet.")
(defconst puppet-ts-align-node-types-regex
(rx bos
(or "hash" "parameter_list" "resource_type" "resource_reference"
"resource_collector" "selector")
eos)
"List of parser items that can be aligned.")
(defun puppet-ts-find-alignment-node (location)
"Identify the innermost node of a block that can be aligned.
Walk the parse tree upwards starting from LOCATION and check the
nodes we find. Terminate the search if we know how to align the
current node. The constant `puppet-ts-align-node-types-regex'
has the regex of the acceptable node types.
Return the node if it is found or nil otherwise."
(save-excursion
(cl-loop for node = (treesit-node-on location location)
then (treesit-node-parent node)
always node
for type = (treesit-node-type node)
until (string-match-p puppet-ts-align-node-types-regex type)
;;do (message "check align node %s" type)
finally return node)))
(defun puppet-ts-align-block ()
"Align the innermost block of parameters, attributes or hashpairs."
(interactive "*")
(save-excursion
;; Skip back over a preceding "}" to perform alignment even when point
;; is just behind the closing bracket.
(if (eq (preceding-char) ?})
(backward-char))
(when-let* ((node (puppet-ts-find-alignment-node (point)))
(beg (treesit-node-start node))
(end (treesit-node-end node)))
;;(message "about to align %S" (treesit-node-type node))
(cond ((string-match-p "\\`resource_\\(?:collector\\|type\\)\\'"
(treesit-node-type node))
;; Restrict alignment to the attributes to avoid including
;; a variable used as title. So we start where the first
;; attribute subtree begins.
(if-let* ((attr (treesit-search-subtree node "attribute"))
(from (treesit-node-start attr)))
(align from end)))
(t
;; Default alignent for all other elements
(align beg end))))))
(defconst puppet-ts-inhibit-electric-alignment
(rx bos (or "comment" "single_quoted_string" "double_quoted_string") eos)
"Node types where electric alignment should not be performed.")
(defun puppet-ts-electric-greater (arg)
"Insert a greater symbol while considering the prefix ARG.
The function checks if the preceding character is an equal sign
to make the fat arrow \"=>\" special. Inserting a fat arrow in
a hash or an attribute list performs automatic alignment. This
can be disabled by customizing `puppet-ts-greater-is-electric'."
(interactive "*P")
(self-insert-command (prefix-numeric-value arg))
(if (and puppet-ts-greater-is-electric
(memq (char-before (1- (point))) '(?= ?+)))
(if-let* ((node (treesit-parent-until
(treesit-node-at (point))
(puppet-ts-node-type-predicate "comment"
"single_quoted_string"
"double_quoted_string"
"attribute_list"
"hash"
"selector")
t))
(type (treesit-node-type node)))
(unless (string-match-p puppet-ts-inhibit-electric-alignment type)
;; Align only when not inside a comment or string
(puppet-ts-align-block)
;; Move point to the start of the value
(cond ((looking-at-p " ")
(forward-char))
((eolp)
(insert " ")))))))
(defun puppet-ts-electric-equal (arg)
"Insert an equal symbol while considering the prefix ARG."
(interactive "*P")
(self-insert-command (prefix-numeric-value arg))
(if puppet-ts-equal-is-electric
(if-let* ((node (treesit-parent-until
(treesit-node-at (point))
(puppet-ts-node-type-predicate "comment"
"single_quoted_string"
"double_quoted_string"
"parameter_list")
t))
(type (treesit-node-type node)))
(unless (string-match-p puppet-ts-inhibit-electric-alignment type)
;; Align only when not inside a comment or string
(puppet-ts-align-block)
;; Move point to the start of the value
(cond ((looking-at-p " ")
(forward-char))
((eolp)
(insert " ")))))))
;;; Skeletons
(defun puppet-ts-dissect-filename (file)
"Return list of file name components for FILE.
The first list element is the basename of FILE and the remaining
elements are the names of each directory from FILE to the root of
the filesystem."
(cl-loop for path = (file-name-sans-extension file)
then (directory-file-name (file-name-directory path))
;; stop iteration at the root of the directory
;; tree (should work for Windows & Unix/Linux)
until (or (string-suffix-p ":" path)
(string-equal (file-name-directory path) path))
collect (file-name-nondirectory path)))
(defun puppet-ts-filename-parser (file)
"Return list of file name components for the Puppet manifest FILE.
The first element of the list will be the module name and the
remaining elements are the relative file name components below
the ‘manifests’ subdirectory. The names of the file name
components are only derived from the file name by using the
Puppet autoloader rules. FILE must be an absolute file name.
The module name \"unidentified\" is returned if a module name
can't be inferred from the file name.
If the directory name contains characters that are not legal for
a Puppet module name, then all leading characters including the
last illegal character are removed from the module name. The
function will for example return ‘foo’ as module name even if the
module is using the ‘puppet-foo’ directory (e.g. for module
development in a user's home directory)."
(if (stringp file)
(let* ((parts (puppet-ts-dissect-filename file))
;; Remove "init" if it is the first element
(compact (if (string-equal (car parts) "init")
(cdr parts)
parts)))
(cons
;; module name with illegal prefixes removed or "unidentified" if
;; FILE is not compliant with the standard Puppet file hierarchy
(replace-regexp-in-string
"^.*[^a-z0-9_]" "" (or (cadr (member "manifests" parts))
"unidentified"))
;; remaining file name components
(cdr (member "manifests" (reverse compact)))))
'("unidentified")))
(defun puppet-ts-file-module-name (file)
"Return the module name for the Puppet class in FILE."
(car (puppet-ts-filename-parser file)))
(defun puppet-ts-file-class-name (file)
"Return the class name for the Puppet class in FILE."
(mapconcat #'identity (puppet-ts-filename-parser file) "::"))
(defun puppet-ts-file-type-name (file)
"Return the Puppet type name for FILE.
FILE must be an absolute file name and should conform to the
standard Puppet module layout. The Puppet type name is returned
if can be derived from FILE. Otherwise nil is returned.
If the function is called with the file name of a provider, the
appropriate type name is returned."
(let ((path (puppet-ts-dissect-filename file)))
(cond ((and (equal (nth 1 path) "type")
(equal (nth 2 path) "puppet"))
(car path))
((and (equal (nth 2 path) "provider")
(equal (nth 3 path) "puppet"))
(cadr path)))))
(defun puppet-ts-file-provider-name (file)
"Return the Puppet provider name for FILE.
FILE must be an absolute file name and should conform to the
standard Puppet module layout. The provider name is returned if
it can be derived from FILE. Otherwise nil is returned."
(let ((path (puppet-ts-dissect-filename file)))
(if (and (equal (nth 2 path) "provider")
(equal (nth 3 path) "puppet"))
(car path))))
(define-skeleton puppet-ts-keyword-class
"Insert \"class\" skeleton."
nil
> "class " (puppet-ts-file-class-name (buffer-file-name)) " (" \n
") {" > \n
> _ "}" > \n)
(define-skeleton puppet-ts-keyword-define
"Insert \"define\" skeleton."
nil
> "define " (puppet-ts-file-class-name (buffer-file-name)) " (" \n
") {" > \n
> _ "}" > \n)
(define-skeleton puppet-ts-keyword-node
"Insert \"node\" skeleton."
nil
> "node " - " {" \n
> _ "}" > \n)
(define-skeleton puppet-ts-type-anchor
"Insert the \"anchor\" resource type."
nil
> "anchor { " - ": }" \n)
(define-skeleton puppet-ts-type-class
"Insert the \"class\" resource type."
nil
> "class { " - ":" \n
"}" > \n)
(define-skeleton puppet-ts-type-exec
"Insert the \"exec\" resource type."
nil
> "exec { " - ":" \n
"path => [ '/bin', '/sbin', '/usr/bin', '/usr/sbin', ]," > \n
"user => 'root'," > \n
"cwd => '/'," > \n
"}" > \n)
(define-skeleton puppet-ts-type-file
"Insert the \"file\" resource type."
nil
> "file { " - ":" \n
"ensure => file," > \n
"owner => 'root'," > \n
"group => 'root'," > \n
"mode => '0644'," > \n
"}" > \n)
(define-skeleton puppet-ts-type-group
"Insert the \"group\" resource type."
nil
> "group { " - ":" \n
"ensure => present," > \n
"}" > \n)
(define-skeleton puppet-ts-type-host
"Insert the \"host\" resource type."
nil
> "host { " - ":" \n
"ensure => present," > \n
"}" > \n)
(define-skeleton puppet-ts-type-notify
"Insert the \"notify\" resource type."
nil
> "notify { " - ": }" \n)
(define-skeleton puppet-ts-type-package
"Insert the \"package\" resource type."
nil
> "package { " - ":" \n
"ensure => present," > \n
"}" > \n)
(define-skeleton puppet-ts-type-service
"Insert the \"service\" resource type."
nil
> "service { " - ":" \n
"ensure => running," > \n
"enable => true," > \n
"}" > \n)
(define-skeleton puppet-ts-type-user
"Insert the \"user\" resource type."
nil
> "user { " - ":" \n
"ensure => present," > \n
"shell => '/bin/bash'," > \n
"password => '*'," > \n
"}" > \n)
;; Xref
(defcustom puppet-ts-module-path
'("/etc/puppetlabs/code/environments/production/modules")
"Directories to search for modules when resolving cross references.
The variable can hold a list of directories to allow more than
a single search location (for example if you use a personal
directory where you do development). Every directory should be
a top-level directory where a module has its own subdirectory
using the module name as subdirectory name (see the Puppet
autoloading rules). The list is searched in order and the search
terminates when the first match is found."
:group 'puppet-ts
:type '(repeat directory))
(defun puppet-ts-module-root (file)
"Return the Puppet module root directory for FILE.
Walk up the directory tree for FILE until a directory is found,
that contains either a \"manifests\", \"types\" or \"lib\"
subdirectory. Return that directory name or nil if no directory
is found."
(locate-dominating-file
file
(lambda (path)
(and (file-accessible-directory-p path)
(or (file-accessible-directory-p (expand-file-name "manifests" path))
(file-accessible-directory-p (expand-file-name "types" path))
(file-accessible-directory-p (expand-file-name "lib" path)))))))
(defun puppet-ts-autoload-name (identifier &optional directory extension)
"Resolve IDENTIFIER into Puppet module and relative autoload name.
Use DIRECTORY as module subdirectory \(defaults to \"manifests\"
and EXTENSION as file extension \(defaults to \".pp\") when
building the name.
Return a cons cell where the first part is the module name and
the second part is a relative file name below that module where
the identifier would be defined according to the Puppet autoload
rules."
(let* ((components (split-string identifier "::"))
(module (car components))
(dirs (cons (or directory "manifests") (butlast (cdr components))))
(file (if (cdr components)
(car (last components))
"init")))
(cons module
(concat (mapconcat #'file-name-as-directory dirs)
file
(or extension ".pp")))))
(defun puppet-ts--xref-backend ()
"The Xref backend for `puppet-ts-mode'."
'puppet)
(cl-defmethod xref-backend-identifier-at-point ((_backend (eql puppet)))
"Return the Puppet identifier at point."
(let ((thing (thing-at-point 'symbol)))
(and thing (substring-no-properties thing))))
(cl-defmethod xref-backend-definitions ((_backend (eql puppet)) identifier)
"Find the definitions of a Puppet resource IDENTIFIER.
First the location of the visited file is checked. Then all
directories from `puppet-ts-module-path' are searched for the
module and file according to Puppet's autoloading rules."
(let* ((resource (downcase (if (string-prefix-p "::" identifier)
(substring identifier 2)
identifier)))
(pupfiles (puppet-ts-autoload-name resource))
(typfiles (puppet-ts-autoload-name resource "types"))
(funfiles (puppet-ts-autoload-name resource "functions"))
(xrefs '()))
(if pupfiles
(let* ((module (car pupfiles))
;; merged list of relative file names to classes/defines/types
(pathlist (mapcar #'cdr (list pupfiles typfiles funfiles)))
;; list of directories where this module might be
(moddirs (mapcar (lambda (dir) (expand-file-name module dir))
puppet-ts-module-path))
;; the regexp to find the resource definition in the file
(resdef (rx bol
(or "class" "define" "function" "type")
(1+ whitespace)
(literal resource)