summaryrefslogtreecommitdiff
path: root/lib/App/DocKnot/Config.pm
blob: de8d8b92299455d69c5dc7460c7f0ba1582faca3 (plain)
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
# Read and return DocKnot package configuration.
#
# Parses the DocKnot package configuration and provides it to other DocKnot
# commands.
#
# SPDX-License-Identifier: MIT

##############################################################################
# Modules and declarations
##############################################################################

package App::DocKnot::Config 2.00;

use 5.024;
use autodie;
use warnings;

use Carp qw(croak);
use File::BaseDir qw(config_files);
use File::ShareDir qw(module_file);
use File::Spec;
use JSON;
use Perl6::Slurp;

# Additional files to load from the metadata directory if they exist.  The
# contents of these files will be added to the configuration in a key of the
# same name.  If the key contains a slash, like foo/bar, it will be stored as
# a nested hash, as $data{foo}{bar}.
our @METADATA_FILES = qw(
  bootstrap
  build/middle
  build/suffix
  debian/summary
  packaging/extra
  support/extra
  test/prefix
  test/suffix
);

##############################################################################
# Helper methods
##############################################################################

# Internal helper routine to return the path of a file from the application
# data.  These data files are installed with App::DocKnot, but each file can
# be overridden by the user via files in $HOME/.config/docknot or
# /etc/xdg/docknot (or whatever $XDG_CONFIG_DIRS is set to).
#
# We therefore try File::BaseDir first (which handles the XDG paths) and fall
# back on using File::ShareDir to locate the data.
#
# $self - The App::DocKnot::Generate object
# @path - The relative path of the file as a list of components
#
# Returns: The absolute path to the application data
#  Throws: Text exception on failure to locate the desired file
sub _appdata_path {
    my ($self, @path) = @_;

    # Try XDG paths first.
    my $path = config_files('docknot', @path);

    # If that doesn't work, use the data that came with the module.
    if (!defined($path)) {
        $path = module_file('App::DocKnot', File::Spec->catfile(@path));
    }
    return $path;
}

# Internal helper routine that locates an application data file, interprets it
# as JSON, and returns the resulting decoded contents.  This uses the relaxed
# parsing mode, so comments and commas after data elements are supported.
#
# $self - The App::DocKnot::Generate object
# @path - The path of the file to load, as a list of components
#
# Returns: Anonymous hash or array resulting from decoding the JSON object
#  Throws: slurp or JSON exception on failure to load or decode the object
sub _load_appdata_json {
    my ($self, @path) = @_;
    my $path = $self->_appdata_path(@path);
    my $json = JSON->new;
    $json->relaxed;
    return $json->decode(scalar(slurp($path)));
}

# Internal helper routine to return the path of a file or directory from the
# package metadata directory.  The resulting file or directory path is not
# checked for existence.
#
# $self - The App::DocKnot::Generate object
# @path - The relative path of the file as a list of components
#
# Returns: The absolute path in the metadata directory
sub _metadata_path {
    my ($self, @path) = @_;
    return File::Spec->catdir($self->{metadata}, @path);
}

# Internal helper routine to read a file from the package metadata directory
# and return the contents.  The file is specified as a list of path
# components.
#
# $self - The App::DocKnot::Generate object
# @path - The path of the file to load, as a list of components
#
# Returns: The contents of the file as a string
#  Throws: slurp exception on failure to read the file
sub _load_metadata {
    my ($self, @path) = @_;
    return slurp($self->_metadata_path(@path));
}

# Like _load_metadata, but interprets the contents of the metadata file as
# JSON and decodes it, returning the resulting object.  This uses the relaxed
# parsing mode, so comments and commas after data elements are supported.
#
# $self - The App::DocKnot::Generate object
# @path - The path of the file to load, as a list of components
#
# Returns: Anonymous hash or array resulting from decoding the JSON object
#  Throws: slurp or JSON exception on failure to load or decode the object
sub _load_metadata_json {
    my ($self, @path) = @_;
    my $data = $self->_load_metadata(@path);
    my $json = JSON->new;
    $json->relaxed;
    return $json->decode($data);
}

##############################################################################
# Public Interface
##############################################################################

# Create a new App::DocKnot::Config object, which will be used for subsequent
# calls.
#
# $class - Class of object to create
# $args  - Anonymous hash of arguments with the following keys:
#   metadata - Path to the directory containing package metadata
#
# Returns: Newly created object
#  Throws: Text exceptions on invalid metadata directory path
sub new {
    my ($class, $args_ref) = @_;

    # Ensure we were given a valid metadata argument.
    my $metadata = $args_ref->{metadata};
    if (!defined($metadata)) {
        $metadata = 'docs/metadata';
    }
    if (!-d $metadata) {
        croak("metadata path $metadata does not exist or is not a directory");
    }

    # Create and return the object.
    my $self = { metadata => $metadata };
    bless($self, $class);
    return $self;
}

# Load the DocKnot package configuration.
#
# $self - The App::DocKnot::Config object
#
# Returns: The package configuration as a dict
#  Throws: autodie exception on failure to read metadata
#          Text exception on inconsistencies in the package data
sub config {
    my ($self) = @_;

    # Load the package metadata from JSON.
    my $data_ref = $self->_load_metadata_json('metadata.json');

    # build.install defaults to true.
    if (!exists($data_ref->{build}{install})) {
        $data_ref->{build}{install} = 1;
    }

    # Load supplemental README sections.  readme.sections will contain a list
    # of sections to add to the README file.
    for my $section ($data_ref->{readme}{sections}->@*) {
        my $title = $section->{title};

        # The file containing the section data will match the title, converted
        # to lowercase and with spaces changed to dashes.
        my $file = lc($title);
        $file =~ tr{ }{-};

        # Load the section content.
        $section->{body} = $self->_load_metadata('sections', $file);

        # If this contains a testing section, that overrides our default.  Set
        # a flag so that the templates know this has happened.
        if ($file eq 'testing') {
            $data_ref->{readme}{testing} = 1;
        }
    }

    # If the package is marked orphaned, load the explanation.
    if ($data_ref->{orphaned}) {
        $data_ref->{orphaned} = $self->_load_metadata('orphaned');
    }

    # If the package has a quote, load the text of the quote.
    if ($data_ref->{quote}) {
        $data_ref->{quote}{text} = $self->_load_metadata('quote');
    }

    # Expand the package license into license text.
    my $license      = $data_ref->{license};
    my $licenses_ref = $self->_load_appdata_json('licenses.json');
    if (!exists($licenses_ref->{$license})) {
        die "Unknown license $license\n";
    }
    my $license_text = slurp($self->_appdata_path('licenses', $license));
    $data_ref->{license} = { $licenses_ref->{$license}->%* };
    $data_ref->{license}{full} = $license_text;

    # Load additional license notices if they exist.
    eval { $data_ref->{license}{notices} = $self->_load_metadata('notices') };

    # Load the standard sections.
    $data_ref->{blurb}        = $self->_load_metadata('blurb');
    $data_ref->{description}  = $self->_load_metadata('description');
    $data_ref->{requirements} = $self->_load_metadata('requirements');

    # Load optional information if it exists.
    for my $file (@METADATA_FILES) {
        my @file = split(m{/}xms, $file);
        if (scalar(@file) == 1) {
            eval { $data_ref->{$file} = $self->_load_metadata(@file) };
        } else {
            eval {
                $data_ref->{ $file[0] }{ $file[1] }
                  = $self->_load_metadata(@file);
            };
        }
    }

    # Return the resulting configuration.
    return $data_ref;
}

##############################################################################
# Module return value and documentation
##############################################################################

1;
__END__

=for stopwords
Allbery DocKnot MERCHANTABILITY NONINFRINGEMENT sublicense CPAN XDG

=head1 NAME

App::DocKnot::Config - Read and return DocKnot package configuration

=head1 SYNOPSIS

    use App::DocKnot;
    use App::DocKnot::Config;
    my $reader = App::DocKnot::Config->new({ metadata => 'docs/metadata' });
    my $config = $reader->config();

=head1 REQUIREMENTS

Perl 5.24 or later and the modules File::BaseDir, File::ShareDir, JSON, and
Perl6::Slurp, all of which are available from CPAN.

=head1 DESCRIPTION

This component of DocKnot reads and returns the configuration for a package.
It takes as input a directory of metadata and returns the configuration
information as a hash.

Additional metadata about specific licenses is loaded via File::BaseDir and
therefore uses XDG paths by default.  This means that license metadata is
found by searching the following paths in order:

=over 4

=item 1.

F<$HOME/.config/docknot>

=item 2.

F<$XDG_CONFIG_DIRS/docknot> (F</etc/xdg/docknot> by default)

=item 3.

Files included in the package.

=back

Default license metadata files are included with the App::DocKnot module and
are used unless more specific configuration files exist.

=head1 CLASS METHODS

=over 4

=item new(ARGS)

Create a new App::DocKnot::Config object.  This should be used for all
subsequent actions.  ARGS should be a hash reference with one or more of the
following keys:

=over 4

=item metadata

The path to the directory containing metadata for a package.  Default:
F<docs/metadata> relative to the current directory.

=back

=back

=head1 INSTANCE METHODS

=over 4

=item config()

Load the metadata for the package and return it as a hash.  The possible keys
of this hash and the possible values are not yet documented.

=back

=head1 AUTHOR

Russ Allbery <rra@cpan.org>

=head1 COPYRIGHT AND LICENSE

Copyright 2013-2019 Russ Allbery <rra@cpan.org>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

=head1 SEE ALSO

L<docknot(1)>

This module is part of the App-DocKnot distribution.  The current version of
App::DocKnot is available from CPAN, or directly from its web site at
L<https://www.eyrie.org/~eagle/software/docknot/>.

=cut

# Local Variables:
# copyright-at-end-flag: t
# End: