summaryrefslogtreecommitdiff
path: root/hack/swagger-check
blob: d564b655405c3d156c124538607d8b305004efaf (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
#!/usr/bin/perl
#
# swagger-check - Look for inconsistencies between swagger and source code
#
package LibPod::SwaggerCheck;

use v5.14;
use strict;
use warnings;

use File::Find;

(our $ME = $0) =~ s|.*/||;
(our $VERSION = '$Revision: 1.7 $ ') =~ tr/[0-9].//cd;

# For debugging, show data structures using DumpTree($var)
#use Data::TreeDumper; $Data::TreeDumper::Displayaddress = 0;

###############################################################################
# BEGIN user-customizable section

our $Default_Dir =  'pkg/api/server';

# END   user-customizable section
###############################################################################

###############################################################################
# BEGIN boilerplate args checking, usage messages

sub usage {
    print  <<"END_USAGE";
Usage: $ME [OPTIONS] DIRECTORY-TO-CHECK

$ME scans all .go files under the given DIRECTORY-TO-CHECK
(default: $Default_Dir), looking for lines of the form 'r.Handle(...)'
or 'r.HandleFunc(...)'. For each such line, we check for a preceding
swagger comment line and verify that the comment line matches the
declarations in the r.Handle() invocation.

For example, the following would be a correctly-matching pair of lines:

    // swagger:operation GET /images/json compat getImages
    r.Handle(VersionedPath("/images/json"), s.APIHandler(compat.GetImages)).Methods(http.MethodGet)

...because http.MethodGet matches GET in the comment, the endpoint
is /images/json in both cases, the APIHandler() says "compat" so
that's the swagger tag, and the swagger operation name is the
same as the APIHandler but with a lower-case first letter.

The following is an inconsistency as reported by this script:

pkg/api/server/register_info.go:
-       // swagger:operation GET /info libpod libpodGetInfo
+       // ................. ... ..... compat
        r.Handle(VersionedPath("/info"), s.APIHandler(compat.GetInfo)).Methods(http.MethodGet)

...because APIHandler() says 'compat' but the swagger comment
says 'libpod'.

OPTIONS:

  --pedantic     Compare operation names (the last part of swagger comment).
                 There are far too many of these inconsistencies to allow us
                 to enable this by default, but it still might be a useful
                 check in some circumstances.

  -v, --verbose  show verbose progress indicators
  -n, --dry-run  make no actual changes

  --help         display this message
  --version      display program name and version
END_USAGE

    exit;
}

# Command-line options.  Note that this operates directly on @ARGV !
our $pedantic;
our $debug   = 0;
our $force   = 0;
our $verbose = 0;
our $NOT     = '';              # print "blahing the blah$NOT\n" if $debug
sub handle_opts {
    use Getopt::Long;
    GetOptions(
        'pedantic'   => \$pedantic,

        'debug!'     => \$debug,
        'dry-run|n!' => sub { $NOT = ' [NOT]' },
        'force'      => \$force,
        'verbose|v'  => \$verbose,

        help         => \&usage,
        man          => \&man,
        version      => sub { print "$ME version $VERSION\n"; exit 0 },
    ) or die "Try `$ME --help' for help\n";
}

# END   boilerplate args checking, usage messages
###############################################################################

############################## CODE BEGINS HERE ###############################

my $exit_status = 0;

# The term is "modulino".
__PACKAGE__->main()                                     unless caller();

# Main code.
sub main {
    # Note that we operate directly on @ARGV, not on function parameters.
    # This is deliberate: it's because Getopt::Long only operates on @ARGV
    # and there's no clean way to make it use @_.
    handle_opts();                      # will set package globals

    # Fetch command-line arguments.  Barf if too many.
    my $dir = shift(@ARGV) || $Default_Dir;
    die "$ME: Too many arguments; try $ME --help\n"                 if @ARGV;

    # Find and act upon all matching files
    find { wanted => sub { finder(@_) }, no_chdir => 1 }, $dir;

    exit $exit_status;
}


############
#  finder  #  File::Find action - looks for 'r.Handle' or 'r.HandleFunc'
############
sub finder {
    my $path = $File::Find::name;
    return if     $path =~ m|/\.|;              # skip dotfiles
    return unless $path =~ /\.go$/;             # Only want .go files

    print $path, "\n"                           if $debug;

    # Read each .go file. Keep a running tally of all '// comment' lines;
    # if we see a 'r.Handle()' or 'r.HandleFunc()' line, pass it + comments
    # to analysis function.
    open my $in, '<', $path
        or die "$ME: Cannot read $path: $!\n";
    my @comments;
    while (my $line = <$in>) {
        if ($line =~ m!^\s*//!) {
            push @comments, $line;
        }
        else {
            # Not a comment line. If it's an r.Handle*() one, process it.
            if ($line =~ m!^\s*r\.Handle(Func)?\(!) {
                handle_handle($path, $line, @comments)
                    or $exit_status = 1;
            }

            # Reset comments
            @comments = ();
        }
    }
    close $in;
}


###################
#  handle_handle  #  Cross-check a 'r.Handle*' declaration against swagger
###################
#
# Returns false if swagger comment is inconsistent with function call,
# true if it matches or if there simply isn't a swagger comment.
#
sub handle_handle {
    my $path     = shift;               # for error messages only
    my $line     = shift;               # in: the r.Handle* line
    my @comments = @_;                  # in: preceding comment lines

    # Preserve the original line, so we can show it in comments
    my $line_orig = $line;

    # Strip off the 'r.Handle*(' and leading whitespace; preserve the latter
    $line =~ s!^(\s*)r\.Handle(Func)?\(!!
        or die "$ME: INTERNAL ERROR! Got '$line'!\n";
    my $indent = $1;

    # Some have VersionedPath, some don't. Doesn't seem to make a difference
    # in terms of swagger, so let's just ignore it.
    $line =~ s!^VersionedPath\(([^\)]+)\)!$1!;
    $line =~ m!^"(/[^"]+)",!
        or die "$ME: $path:$.: Cannot grok '$line'\n";
    my $endpoint = $1;

    # FIXME: in older code, '{name:..*}' meant 'nameOrID'. As of 2020-02
    # it looks like most of the '{name:..*}' entries are gone, except for one.
###FIXME-obsolete?    $endpoint =~ s|\{name:\.\.\*\}|{nameOrID}|;

    # e.g. /auth, /containers/*/rename, /distribution, /monitor, /plugins
    return 1 if $line =~ /\.UnsupportedHandler/;

    #
    # Determine the HTTP METHOD (GET, POST, DELETE, HEAD)
    #
    my $method;
    if ($line =~ /generic.VersionHandler/) {
        $method = 'GET';
    }
    elsif ($line =~ m!\.Methods\((.*)\)!) {
        my $x = $1;

        if ($x =~ /Method(Post|Get|Delete|Head)/) {
            $method = uc $1;
        }
        elsif ($x =~ /\"(HEAD|GET|POST)"/) {
            $method = $1;
        }
        else {
            die "$ME: $path:$.: Cannot grok $x\n";
        }
    }
    else {
        warn "$ME: $path:$.: No Methods in '$line'\n";
        return 1;
    }

    #
    # Determine the SWAGGER TAG. Assume 'compat' unless we see libpod; but
    # this can be overruled (see special case below)
    #
    my $tag = ($endpoint =~ /(libpod)/ ? $1 : 'compat');

    #
    # Determine the OPERATION. *** NOTE: This is mostly useless! ***
    # In an ideal world the swagger comment would match actual function call;
    # in reality there are over thirty mismatches. Use --pedantic to see.
    #
    my $operation = '';
    if ($line =~ /(generic|handlers|compat)\.(\w+)/) {
        $operation = lcfirst $2;
        if ($endpoint =~ m!/libpod/! && $operation !~ /^libpod/) {
            $operation = 'libpod' . ucfirst $operation;
        }
    }
    elsif ($line =~ /(libpod)\.(\w+)/) {
        $operation = "$1$2";
    }

    # Special case: the following endpoints all get a custom tag
    if ($endpoint =~ m!/(volumes|pods|manifests)/!) {
        $tag = $1;
        $operation =~ s/^libpod//;
        $operation = lcfirst $operation;
    }

    # Special case: anything related to 'events' gets a system tag
    if ($endpoint =~ m!/events!) {
        $tag = 'system';
    }

    # Special case: /changes is libpod even though it says compat
    if ($endpoint =~ m!/changes!) {
        $tag = 'libpod';
    }

    state $previous_path;                # Previous path name, to avoid dups

    #
    # Compare actual swagger comment to what we expect based on Handle call.
    #
    my $expect = " // swagger:operation $method $endpoint $tag $operation ";
    my @actual = grep { /swagger:operation/ } @comments;

    return 1 if !@actual;         # No swagger comment in file; oh well

    my $actual = $actual[0];

    # By default, don't compare the operation: there are far too many
    # mismatches here.
    if (! $pedantic) {
        $actual =~ s/\s+\S+\s*$//;
        $expect =~ s/\s+\S+\s*$//;
    }

    # (Ignore whitespace discrepancies)
    (my $a_trimmed = $actual) =~ s/\s+/ /g;

    return 1 if $a_trimmed eq $expect;

    # Mismatch. Display it. Start with filename, if different from previous
    print "\n";
    if (!$previous_path || $previous_path ne $path) {
        print $path, ":\n";
    }
    $previous_path = $path;

    # Show the actual line, prefixed with '-' ...
    print "- $actual[0]";
    # ...then our generated ones, but use '...' as a way to ignore matches
    print "+ $indent//";
    my @actual_split = split ' ', $actual;
    my @expect_split = split ' ', $expect;
    for my $i (1 .. $#actual_split) {
        print " ";
        if ($actual_split[$i] eq ($expect_split[$i]||'')) {
            print "." x length($actual_split[$i]);
        }
        else {
            # Show the difference. Use terminal highlights if available.
            print "\e[1;37m"            if -t *STDOUT;
            print $expect_split[$i];
            print "\e[m"                if -t *STDOUT;
        }
    }
    print "\n";

    # Show the r.Handle* code line itself
    print "  ", $line_orig;

    return;
}

1;