def get_current_rev(org_label, project_label, id, nxs): data = nxs.resolvers.fetch(org_label=org_label, project_label=project_label, id=id) if "_rev" not in data: utils.error("No _rev present in %s payload" % id) return data["_rev"]
def show_identities(_json, pretty): nxs = utils.get_nexus_client() try: response = nxs.identities.fetch() if _json: utils.print_json(response, colorize=pretty) else: columns = ["Id", "Type", "Realm", "User", "Group"] table = PrettyTable(columns) for c in columns: table.align[c] = "l" for i in response["identities"]: realm = "" if "realm" in i: realm = i["realm"] user = "" if "subject" in i: user = i["subject"] group = "" if "group" in i: realm = i["group"] table.add_row([i["@id"], i["@type"], realm, user, group]) print(table) except nxs.HTTPError as e: utils.print_json(e.response.json(), colorize=True) utils.error(str(e))
def delete(profile): config = utils.get_cli_config() if profile not in config: utils.error("Could not find profile '%s' in CLI config" % profile) config.pop(profile, None) utils.save_cli_config(config) print("Profile deleted.")
def _list(_org_label, _prj_label, deprecated, _from, size, _type, _json, pretty): _org_label = utils.get_organization_label(_org_label) _prj_label = utils.get_project_label(_prj_label) nxs = utils.get_nexus_client() try: response = nxs.views.list(org_label=_org_label, project_label=_prj_label, pagination_from=_from, pagination_size=size, deprecated=deprecated, type=_type) if _json: utils.print_json(response, colorize=pretty) else: table = PrettyTable(['Id', 'Type', 'Revision', 'Deprecated']) table.align["Id"] = "l" table.align["Type"] = "l" table.align["Revision"] = "l" table.align["Deprecated"] = "l" for r in response["_results"]: types = utils.format_json_field(r, "@type") table.add_row([r["@id"], types, r["_rev"], r["_deprecated"]]) print(table) except nxs.HTTPError as e: utils.error(str(e)) utils.print_json(e.response.json(), colorize=True)
def make_public(_org_label, _prj_label, _replace, _json, pretty): _org_label = utils.get_organization_label(_org_label) _prj_label = utils.get_project_label(_prj_label) nxs = utils.get_nexus_client() try: path = _org_label + '/' + _prj_label utils.warn("You are about to make the data in your project public to the world.") input("Press <ENTER> to continue, CTRL+C to cancel...") response = nxs.acls.fetch(subpath=path) count = len(response["_results"]) if count > 1: utils.error("More than one ACL matching: %d" % count) elif count == 0: utils.warn("No ACL found specifically for this organization '%s' and project '%s'." % (_org_label, _prj_label)) current_rev = 0 else: current_rev = response["_results"][0]['_rev'] _identities = [_ANONYMOUS_] _permissions = [_PROJECTS_READ_, _RESOURCES_READ_, _VIEWS_QUERY_] if _replace: print("Replacing existing ACLs on project '%s' in organization '%s'" % (_prj_label, _org_label)) response = nxs.acls.replace(subpath=path, identities=_identities, permissions=[_permissions], rev=current_rev) else: print("Adding to existing ACLs on project '%s' in organization '%s'" % (_prj_label, _org_label)) response = nxs.acls.append(subpath=path, identities=_identities, permissions=[_permissions], rev=current_rev) if _json: utils.print_json(response, colorize=pretty) except nxs.HTTPError as e: utils.print_json(e.response.json(), colorize=True) utils.error(str(e))
def _list(_from, size, _json, pretty): nxs = utils.get_nexus_client() try: response = nxs.organizations.list(pagination_from=_from, pagination_size=size) if _json: utils.print_json(response, colorize=pretty) else: table = PrettyTable(['Label', 'Description', 'Id', 'Deprecated']) table.align["Label"] = "l" table.align["Description"] = "l" table.align["Id"] = "l" table.align["Deprecated"] = "l" for r in response["_results"]: if "description" in r: table.add_row([ r["_label"], r["description"], r["@id"], r["_deprecated"] ]) else: table.add_row( [r["_label"], "", r["@id"], r["_deprecated"]]) print(table) except nxs.HTTPError as e: utils.print_json(e.response.json(), colorize=True) utils.error(str(e))
def get_query_from_payload_xor_data_otherwise_editor(_payload, file, default_query, file_prefix): """ If a payload or a file is provided, use it. Otherwise, propose the user an editor with a default query. :param _payload: the query as a dict or str :param file: the filename from which to load the query :param default_query: the query to load in the editor :param file_prefix: the prefix of the editor file to save in the current dir :return: the query as text. """ if _payload is not None and file is not None: utils.error("--data and --file are mutually exclusive.") if _payload is not None: if isinstance(_payload, dict): data = json.dumps(_payload, indent=2) else: data = _payload elif file is not None: f = open(file, "r") data = f.read() f.close() else: new_file, filename = tempfile.mkstemp(dir=".", prefix=file_prefix+"-") print("Opening an editor: %s" % filename) f = open(filename, "w") q = default_query if isinstance(default_query, dict): q = json.dumps(default_query, indent=2) f.write(q) f.close() click.edit(filename=filename) f = open(filename, "r") data = f.read() f.close() return data
def update(id, _org_label, _prj_label, _payload): _org_label = utils.get_organization_label(_org_label) _prj_label = utils.get_project_label(_prj_label) nxs = utils.get_nexus_client() try: data = nxs.resources.fetch(org_label=_org_label, project_label=_prj_label, schema_id='_', resource_id=id) data_md5_before = utils.generate_nexus_payload_checksum(data) current_revision = data["_rev"] if _payload is not None: data = json.loads(_payload) else: # If no payload given, load up the entry in a text file and open default editor new_file, filename = tempfile.mkstemp() print("Opening an editor: %s" % filename) f = open(filename, "w") f.write(json.dumps(data, indent=2)) f.close() click.edit(filename=filename) f = open(filename, "r") data = json.loads(f.read()) f.close() os.remove(filename) data_md5_after = utils.generate_nexus_payload_checksum(data) if data_md5_before == data_md5_after: print("No change in resource, aborting update.") else: nxs.resources.update(resource=data, rev=current_revision) print("Resource updated.") except nxs.HTTPError as e: utils.print_json(e.response.json(), colorize=True) utils.error(str(e))
def view_token(): """Show token for current profile.""" config = utils.get_cli_config() _token = None selected = None for key in config.keys(): if nexuscli.config.SELECTED_KEY in config[key] and config[key][ nexuscli.config.SELECTED_KEY] is True: selected = key if TOKEN_KEY in config[key]: _token = config[key][TOKEN_KEY] print(_token) decoded = jwt.decode(_token, verify=False) print("\nDecoded token:") utils.print_json(decoded, colorize=True) expiry_utc = datetime.utcfromtimestamp(decoded['exp']) expires_in = expiry_utc.timestamp() - datetime.now().timestamp( ) if expires_in > 0: when = "in %s" % utils.print_time(expires_in) message_color = 'green' else: when = "%s ago" % utils.print_time(abs(expires_in)) message_color = 'red' msg = "\nExpiry: %s (%s)" % ( utils.datetime_from_utc_to_local(expiry_utc), when) click.echo(click.style(msg, fg=message_color)) if _token is None: if selected is None: utils.error("You haven't selected a profile.") else: utils.error('No tokens in selected profile: %s' % selected)
def query_sparql(_org_label, _prj_label, id, _payload, file, _json, pretty): _org_label = utils.get_organization_label(_org_label) _prj_label = utils.get_project_label(_prj_label) nxs = utils.get_nexus_client() try: default_query = "SELECT * WHERE { ?s ?p ?o } LIMIT 10" data = get_query_from_payload_xor_data_otherwise_editor( _payload, file, default_query, file_prefix="query-sparql") response = nxs.views.query_sparql(org_label=_org_label, project_label=_prj_label, query=data, view_id=id) if _json: utils.print_json(response, colorize=pretty) else: vars = response["head"]["vars"] table = PrettyTable(vars) for v in vars: table.align[v] = "l" for b in response["results"]["bindings"]: cells = [] for v in vars: cells.append(b[v]["value"]) table.add_row(cells) print(table) except nxs.HTTPError as e: utils.error(str(e)) utils.print_json(e.response.json(), colorize=True)
def create(label, _org_label, description, base, vocab, _api_mapping, _json, pretty): _org_label = utils.get_organization_label(_org_label) try: mappings = None if _api_mapping is not None: mappings = [] for am in _api_mapping: if "=" not in am: utils.error( "Invalid API Mapping, it should be in the format <prefix>=<URL>: %s" % am) key, value = am.split("=", 1) entry = {"prefix": key, "namespace": value} mappings.append(entry) nxs = utils.get_nexus_client() response = nxs.projects.create(org_label=_org_label, project_label=label, description=description, api_mappings=mappings, vocab=vocab, base=base) print("Project created (id: %s)" % response["@id"]) if _json: utils.print_json(response, colorize=pretty) except nxs.HTTPError as e: utils.print_json(e.response.json(), colorize=True) utils.error(str(e))
def update(id, _org_label, _prj_label, _payload): _org_label = utils.get_organization_label(_org_label) _prj_label = utils.get_project_label(_prj_label) nxs = utils.get_nexus_client() try: view = nxs.views.fetch(org_label=_org_label, project_label=_prj_label, view_id=id) view_md5_before = utils.generate_nexus_payload_checksum(view, debug=True) current_revision = view["_rev"] if _payload is not None: view = json.loads(_payload) else: # If no payload given, load up the entry in a text file and open default editor new_file, filename = tempfile.mkstemp() print("Opening an editor: %s" % filename) f = open(filename, "w") f.write(json.dumps(view, indent=2)) f.close() click.edit(filename=filename) f = open(filename, "r") view = json.loads(f.read()) f.close() os.remove(filename) view_md5_after = utils.generate_nexus_payload_checksum(view, debug=True) if view_md5_before == view_md5_after: print("No change in view, aborting update.") else: nxs.views.update_es(esview=view, rev=current_revision) print("View updated.") except nxs.HTTPError as e: utils.error(str(e)) utils.print_json(e.response.json(), colorize=True)
def fetch(label, revision, pretty): nxs = utils.get_nexus_client() try: response = nxs.realms.fetch(label, revision) utils.print_json(response, colorize=pretty) except nxs.HTTPError as e: print(e.response.json()) utils.error(str(e))
def update(label, data, _json, pretty): nxs = utils.get_nexus_client() try: response = nxs.realms.replace_(label, data, data['_rev']) if _json: utils.print_json(response, colorize=pretty) utils.success("Realm updated.") except nxs.HTTPError as e: print(e.response.json()) utils.error(str(e))
def create(label, name, _open_id_config, logo, _json, pretty): nxs = utils.get_nexus_client() try: response = nxs.realms.create(label, name, _open_id_config, logo) if _json: utils.print_json(response, colorize=pretty) utils.success("Realm created.") except nxs.HTTPError as e: print(e.response.json()) utils.error(str(e))
def select(profile): config = utils.get_cli_config() if profile not in config: utils.error("Could not find profile '%s' in CLI config" % delete) for key in config.keys(): if _SELECTED_KEY_ in config[key] and key != select: config[key].pop(_SELECTED_KEY_, None) config[profile][_SELECTED_KEY_] = True utils.save_cli_config(config) print("Selected profile: %s" % profile)
def _list(): nxs = utils.get_nexus_client() try: response = nxs.realms.list() utils.print_json(response, colorize=True) for r in response["_results"]: print(r["name"], r["_deprecated"]) except nxs.HTTPError as e: print(e.response.json()) utils.error(str(e))
def fetch(label, revision, pretty): nxs = utils.get_nexus_client() try: response = nxs.organizations.fetch(org_label=label, rev=revision) if revision is not None and response["_rev"] != revision: utils.error("Revision '%s' does not exist" % revision) utils.print_json(response, colorize=pretty) except nxs.HTTPError as e: utils.print_json(e.response.json(), colorize=True) utils.error(str(e))
def create(label, description, _json, pretty): nxs = utils.get_nexus_client() try: response = nxs.organizations.create(org_label=label, description=description) print("Organization created (id: %s)" % response["@id"]) if _json: utils.print_json(response, colorize=pretty) except nxs.HTTPError as e: utils.print_json(e.response.json(), colorize=True) utils.error(str(e))
def current(): config = utils.get_cli_config() profile, selected_config = utils.get_selected_deployment_config(config) if selected_config is None: utils.error("You must first select a profile using the 'profiles' command") default_project = utils.get_default_project() if default_project is not None: print(default_project) else: utils.error("No default project selected in profile '%s'" % profile)
def deprecate(label, _json, pretty): nxs = utils.get_nexus_client() try: response = nxs.realms.deprecate(label) if _json: utils.print_json(response, colorize=pretty) utils.success("Realm deprecated.") except nxs.HTTPError as e: print(e.response.json()) utils.error(str(e))
def select(label, _json, pretty): nxs = utils.get_nexus_client() try: response = nxs.realms.fetch(label) if _json: utils.print_json(response, colorize=pretty) utils.set_default_realm(label, response['_issuer']) utils.success("Realm selected.") except nxs.HTTPError as e: print(e.response.json()) utils.error(str(e))
def create(profile, url): config = utils.get_cli_config() if profile in config and 'url' in config[profile]: utils.error("This deployment already exist (%s) with url: %s" % (create, config[create])) url = validate_nexus_url(url) config[profile] = {_URL_KEY_: url} if len(config) == 1: config[profile][_SELECTED_KEY_] = True utils.save_cli_config(config) print("Profile created.")
def validate_nexus_url(url): try: import nexussdk as nxs url = url.rstrip("/") nxs.config.set_environment(url) nxs.identities.fetch() except nxs.HTTPError as e: utils.error( "Provided URL isn't valid or the service isn't responding: %s" % url) return url
def fetch(id, _org_label, _prj_label, schema, revision, tag, pretty): _org_label = utils.get_organization_label(_org_label) _prj_label = utils.get_project_label(_prj_label) nxs = utils.get_nexus_client() try: response = nxs.resources.fetch(org_label=_org_label, project_label=_prj_label, schema_id=schema, resource_id=id, rev=revision, tag=tag) utils.print_json(response, colorize=pretty) except nxs.HTTPError as e: utils.print_json(e.response.json(), colorize=True) utils.error(str(e))
def _list(_org_label, _prj_label, deprecated, _from, size, search, _json, pretty): _org_label = utils.get_organization_label(_org_label) _prj_label = utils.get_project_label(_prj_label) nxs = utils.get_nexus_client() try: response = nxs.schemas.list(org_label=_org_label, project_label=_prj_label, pagination_from=_from, pagination_size=size, deprecated=deprecated, full_text_search_query=search) if _json: utils.print_json(response, colorize=pretty) else: columns = [ 'Id', 'Types', 'Label', 'Imports', 'NodeShapes', 'PropertyShapes', 'Revision', 'Deprecated' ] table = PrettyTable(columns) for c in columns: table.align[c] = "l" for r in response["_results"]: types = utils.format_json_field(r, "@type") # Get extra info from the schema itself schema = nxs.schemas.fetch(org_label=_org_label, project_label=_prj_label, schema_id=r["@id"]) imports = utils.format_json_field(schema, "imports") node_shapes = get_shapes_id_by_node_kind( schema, ["sh:NodeShape", "NodeShape"]) property_shapes = get_shapes_id_by_node_kind( schema, ["sh:PropertyShapes", "PropertyShapes"]) dummy_payload = { "nodes": node_shapes, "properties": property_shapes } nodes = utils.format_json_field(dummy_payload, "nodes") properties = utils.format_json_field(dummy_payload, "properties") label = "" if "label" in schema: label = schema["label"] table.add_row([ r["@id"], types, label, imports, nodes, properties, r["_rev"], r["_deprecated"] ]) print(table) except nxs.HTTPError as e: utils.print_json(e.response.json(), colorize=True) utils.error(str(e))
def statistics(_org_label, _prj_label, id, pretty): _org_label = utils.get_organization_label(_org_label) _prj_label = utils.get_project_label(_prj_label) nxs = utils.get_nexus_client() try: response = nxs.views.stats(org_label=_org_label, project_label=_prj_label, view_id=id) utils.print_json(response, colorize=pretty) except nxs.HTTPError as e: utils.error(str(e)) utils.print_json(e.response.json(), colorize=True)
def update(id, _org_label, _prj_label, _projects, _identities, _priority, _resources_types, _type, _payload): _org_label = utils.get_organization_label(_org_label) _prj_label = utils.get_project_label(_prj_label) nxs = utils.get_nexus_client() try: data = nxs.resolvers.fetch(org_label=_org_label, project_label=_prj_label, id=id) current_revision = data["_rev"] data_md5_before = utils.generate_nexus_payload_checksum(data) if _priority is not None and _identities is not None and _projects is not None: response = nxs.resolvers.update(org_label=_org_label, project_label=_prj_label, projects=_projects, identities=_identities, _priority=_priority, id=id, rev=current_revision, resources_types=_resources_types) else: if _payload is not None: data = json.loads(_payload) else: # If no payload given, load up the entry in a text file and open default editor new_file, filename = tempfile.mkstemp() print("Opening an editor: %s" % filename) f = open(filename, "w") f.write(json.dumps(data, indent=2)) f.close() click.edit(filename=filename) f = open(filename, "r") data = json.loads(f.read()) f.close() os.remove(filename) data_md5_after = utils.generate_nexus_payload_checksum(data) if data_md5_before == data_md5_after: print("No change in resolver, aborting update.") else: encoded_id = encode_url(id) nxs.resolvers.update_(path=[ nxs.resolvers.SEGMENT, _org_label, _prj_label, encoded_id ], payload=data, rev=current_revision) print("Resolver updated.") except nxs.HTTPError as e: utils.error(str(e)) utils.print_json(e.response.json(), colorize=True)
def deprecate(label, _json, pretty): nxs = utils.get_nexus_client() try: response = nxs.organizations.fetch(label) if _json: utils.print_json(response, colorize=pretty) response = nxs.organizations.deprecate(org_label=label, rev=response["_rev"]) if _json: utils.print_json(response, colorize=pretty) print("Organization '%s' was deprecated." % label) except nxs.HTTPError as e: utils.print_json(e.response.json(), colorize=True) utils.error(str(e))
def select(label): nxs = utils.get_nexus_client() try: nxs.organizations.fetch(org_label=label) except nxs.HTTPError as e: if e.response.status_code == 404: utils.error("Could not find organization with label '%s'." % label) else: # unexpected error utils.print_json(e.response.json(), colorize=True) utils.error(str(e)) utils.set_default_organization(label) print("organization selected.")