Last active
September 16, 2021 14:59
-
-
Save PaulGWebster/24e543ee33b664f18e756f70c370df17 to your computer and use it in GitHub Desktop.
OpenAPI mojo/operational id auto generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
use v5.28; | |
use warnings; | |
use strict; | |
use experimental 'signatures'; | |
use Getopt::Long qw(GetOptionsFromArray); | |
use Carp qw(croak cluck longmess shortmess confess); | |
use Data::Dumper; | |
use JSON::MaybeXS; | |
my $path = 'openapi.spec'; | |
my $json = JSON::MaybeXS->new(pretty => 1); | |
my $decoded_content = $json->decode(slurp($path)); | |
my $modified_content = generate_idset($decoded_content); | |
my $encoded_content = $json->encode($modified_content); | |
open(my $fh,'>',$path . '.modified'); | |
print $fh $encoded_content; | |
close($fh); | |
sub generate_idset($content) { | |
my $root = 'paths'; | |
foreach my $path (keys %{$content->{$root}}) { | |
foreach my $method (keys %{$content->{$root}->{$path}}) { | |
if ($method !~ m#^get|post|put|delete|patch|head|options|trace$#i) { next } | |
my @psplit = split(/\//,$path); | |
my @pname = (); | |
push @pname,'root'; | |
foreach my $path_element (@psplit) { | |
if (!$path_element || $path_element =~ m/^\s+$/) { next } | |
if ($path_element =~ m#^{(.*)}$#) { $path_element = $1 } | |
push @pname,lc($path_element); | |
} | |
push @pname,lc($method); | |
my $newname = join('_',@pname); | |
$content->{$root}->{$path}->{$method}->{'operationId'} = $newname; | |
$content->{$root}->{$path}->{$method}->{'x-mojo-name'} = $newname; | |
} | |
} | |
return $content; | |
} | |
sub slurp($path) { | |
if (!-e $path) { die "No such file" } | |
local $/; | |
open(my $fh,'<',$path); | |
my $file = <$fh>; | |
close($fh); | |
return $file; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
May be worth changing line 44 to detect operationId and if it exists set line 45 to it, if an existing schema!