add AUR.pm
[aurutils.git] / perl / AUR / Json.pm
blob5fc5650ae147ba0d8365e1c29d9079a746ceab1a
1 package AUR::Json;
2 use strict;
3 use warnings;
4 use v5.20;
6 use Exporter qw(import);
7 our @EXPORT = qw(parse_json parse_json_aur write_json);
8 our $VERSION = 'unstable';
10 =head1 NAME
12 AUR::Json - Perl interface to AurJson
14 =head1 SYNOPSIS
16 use AUR::Json qw(parse_json_aur write_json);
18 my $json;
19 my @results = parse_json_aur($json);
20 my $object = parse_json($json);
21 write_json($object);
23 =head1 DESCRIPTION
25 This module provides Perl aur(1) scripts a coherent way to deal with
26 AurJson responses. In particular, parse_json_aur() returns an array of
27 package results for variable AUR inputs (both from AurJson and
28 metadata archives.
30 If JSON::XS is available, this module will use it for JSON
31 parsing. JSON::PP shipped with Perl is used as a fallback.
33 TODO: The interface is in its early stages and is prone to change in
34 later versions. Possible additions include AUR types for common use
35 with aur-format(1) and aur-search(1).
37 =head1 AUTHORS
39 Alad Wenter <https://github.com/AladW/aurutils>
41 =cut
43 my $aur_json;
45 # Fallback to slower perl-based JSON parsing
46 if (eval { require JSON::XS; 1 }) {
47 $aur_json = JSON::XS->new;
49 else {
50 require JSON::PP;
51 $aur_json = JSON::PP->new;
54 sub parse_json {
55 my $str = shift;
56 my $obj = $aur_json->incr_parse($str)
57 or die __PACKAGE__ . ": expected JSON object or array at beginning of string";
58 $aur_json->incr_reset();
60 return $obj;
63 sub parse_json_aur {
64 my $str = shift;
65 my $obj = parse_json($str);
67 # Possible AUR responses:
68 # - JSON arrays: REST (suggests), metadata archives (pkgnames.git, pkgbases.git)
69 # - JSON hashes, `results` array: REST (info, search)
70 # - JSON hashes: metadata archives (pkgname.json, pkgbase.json)
71 if (ref($obj) eq 'HASH' and defined($obj->{'results'})) {
72 my $error = $obj->{'error'};
74 if (defined($error)) {
75 say STDERR __PACKAGE__ . ': response error (' . $error . ')';
76 exit(4);
78 return @{$obj->{'results'}};
80 elsif (ref($obj) eq 'HASH') {
81 return values %{$obj};
83 elsif (ref($obj) eq 'ARRAY') {
84 return @{$obj};
86 else {
87 say STDERR __PACKAGE__ . ": not an array or hash";
88 exit(4);
92 sub write_json {
93 my $obj = shift;
94 say $aur_json->canonical()->encode($obj);
97 # vim: set et sw=4 sts=4 ft=perl: