Skip to content

Commit

Permalink
DXE-2766 Merge pull request #42 from akamai/release/v2.1.2
Browse files Browse the repository at this point in the history
release v2.1.2
  • Loading branch information
dawiddzhafarov authored Jun 22, 2023
2 parents 6c966ad + 15b5b9e commit a99370a
Show file tree
Hide file tree
Showing 11 changed files with 271 additions and 165 deletions.
8 changes: 8 additions & 0 deletions .pylintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[BASIC]
disable=
redefined-builtin,
unspecified-encoding

good-names=
rc,
httpie-edgegrid
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
# HTTPIE EDGEGRID RELEASE NOTES

## 2.1.2 (2023-06-22)

### Bug fixes

* Fix bug returning unexpected error when performing basic API call ([I#34](https://github.com/akamai/httpie-edgegrid/issues/34))

### Enhancements

* Update `httpie` and `pyOpenSSL` dependencies

## 2.1.1 (2022-09-27)

### Enhancements
Expand Down
32 changes: 32 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
PYTHON = python3.10

.PHONY: help
help:
@echo " install install all dev and production dependencies (virtualenv is created as venv)"
@echo " clean remove unwanted stuff"
@echo " lint check style"
@echo " test run tests"
@echo " coverage run tests with code coverage"

.PHONY: install
install:
$(PYTHON) -m venv venv; . venv/bin/activate; $(PYTHON) -m pip install -r requirements_dev.txt

.PHONY: clean
clean:
rm -fr venv

.PHONY: lint
lint:
@. venv/bin/activate; find . -iname "*.py" -not -path "./venv/*" -not -path "./test/*" -exec echo "Linting {}" \; -exec pylint -rn {} \;

.PHONY: test
test:
@. venv/bin/activate; pytest -v --junitxml test/tests.xml

.PHONY: coverage
coverage:
@. venv/bin/activate; pytest --cov-report xml:test/coverage/cobertura-coverage.xml --cov=gen_edgerc --cov=httpie_edgegrid test/

.PHONY: all
all: clean install lint test coverage
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ Once you have the credentials set up, here is an example of what an Akamai OPEN
Making the diagnostic-tools API [locations]{.title-ref} call:

``` bash
% http --auth-type edgegrid -a default: :/diagnostic-tools/v2/ghost-locations/available
% http --auth-type edgegrid -a default: :/edge-diagnostics/v1/edge-locations
```

## Parameters
Expand Down
141 changes: 92 additions & 49 deletions gen_edgerc.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@
# Usage: python gen_edgerc.py -s <section_name> -f <export_file>

""" Copyright 2015 Akamai Technologies, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Expand All @@ -28,36 +28,21 @@
from configparser import ConfigParser
from os.path import expanduser

# This script will create a configuration section with the name of the client in your
# ~/.edgerc credential store. Many of the sample applications use the a section
# named 'default' for ease when running them during API Bootcamps.


def generate_edgerc(arguments, edgerc_file, enable_interruption):
if arguments.cred_file:
print("+++ Reading from EdgeGrid credentials file:", arguments.cred_file)
with open(os.path.expanduser(arguments.cred_file), "r") as credFile:
text = credFile.read()
credFile.close()
else:
print("""After authorizing your client in the {OPEN} API Administration tool,
export the credentials and paste the contents of the export file below,
followed by control-D.
""")
sys.stdout.write('>>>\n')
text = sys.stdin.read()
sys.stdout.write('<<<\n\n')

# load the cred data
fieldlist = text.split()
index = 0
fields = {}
def generate_edgerc(arguments: argparse.Namespace,
edgerc_file: str,
enable_interruption: bool = True):
"""
Creates a configuration section with the name of the client in your
~/.edgerc credential store. Many of the sample applications use the a section
named 'default' for ease when running them during API Bootcamps.
# Parse the cred data
while index < len(fieldlist):
if re.search(r':$', fieldlist[index]):
fields[fieldlist[index]] = fieldlist[index + 1]
index += 1
Args:
arguments (argparse.Namespace): arguments parsed from the cmd
edgerc_file (str): a path to '.edgerc'
enable_interrupbion (bool): if True the script will interrupt with prompts (default=True)
"""
fields = get_credentials_data(arguments.cred_file)

# Determine the section name giving precedence to -s value
if arguments.config_section:
Expand All @@ -66,7 +51,7 @@ def generate_edgerc(arguments, edgerc_file, enable_interruption):
else:
section_name = fields['Name:']
section_name_pretty = fields['Name:']
print("+++ Found client credentials with the name: %s" % section_name)
print(f"+++ Found client credentials with the name: {section_name}")

# Fix up default sections
if section_name.lower() == "default":
Expand All @@ -78,27 +63,29 @@ def generate_edgerc(arguments, edgerc_file, enable_interruption):

# If this is a new file, create it
if not os.path.isfile(edgerc_file):
print("+++ Creating new credentials file: %s" % edgerc_file)
open(edgerc_file, 'a+').close()
print(f"+++ Creating new credentials file: {edgerc_file}")
with open(edgerc_file, 'a+'):
pass
else:
print("+++ Found credentials file: %s" % edgerc_file)
print(f"+++ Found credentials file: {edgerc_file}")

# Recommend default section name if not present
orig_config.read(edgerc_file)
if 'default' not in orig_config.sections() and enable_interruption:
reply = str(input(
'\nThe is no default section in ~/.edgerc, do you want to use these credentials as default? [y/n]: '
f'\nThe is no default section in {edgerc_file}, ' +
'do you want to use these credentials as default? [y/n]: '
)).lower().strip()
print()
if reply[0] == 'y':
section_name = "----DEFAULT----"
section_name_pretty = "default"

if section_name_pretty in orig_config.sections():
print(">>> Replacing section: %s" % section_name_pretty)
print(f">>> Replacing section: {section_name_pretty}")
replace_section = True
else:
print("+++ Creating section: %s" % section_name_pretty)
print(f"+++ Creating section: {section_name_pretty}")
replace_section = False

if enable_interruption:
Expand All @@ -111,45 +98,101 @@ def generate_edgerc(arguments, edgerc_file, enable_interruption):
# We need a line for the output to look nice
print()

add_section(edgerc_file, section_name,
section_name_pretty, fields, replace_section)

print("\nDone. Please verify your credentials with the verify_creds.py script.\n")


def get_credentials_data(cred_path: str) -> dict[str, str]:
"""
Returns credentials data from provided file or input in a key-value format.
Args:
cred_path (str): a path to file with credentials
Returns:
dict[str, str]: key-value pairs found in the provided credentials
"""
if cred_path:
print("+++ Reading from EdgeGrid credentials file:", cred_path)
with open(os.path.expanduser(cred_path), "r") as cred_file:
text = cred_file.read()
else:
print("""After authorizing your client in the {OPEN} API Administration tool,
export the credentials and paste the contents of the export file below,
followed by control-D.
""")
sys.stdout.write('>>>\n')
text = sys.stdin.read()
sys.stdout.write('<<<\n\n')

return parse_credentials_data(text)


def parse_credentials_data(cred_text: str) -> dict[str, str]:
"""
Finds key-value pairs in the passed data.
Args:
cred_text (str): content of credentials
Returns:
dict[str, str]: key-value pairs found in the provided credentials
"""
fieldlist = cred_text.split()
fields = {}

for index, field in enumerate(fieldlist):
if re.search(r':$', field):
fields[field] = fieldlist[index + 1]

return fields


def add_section(edgerc_file, section_name, section_name_pretty, fields, replace_section):
"""
Adds a section in edgerc file.
Args:
edgerc_file (str) - path to an edgerc file
section_name (str) - section name to be added/replaced
section_name_pretty (str) - section name used in outputs
fields (dict[str, str]) - credentials in key-value format
replace_section (bool) - True if section already exists and needs to be removed first
"""
# If we have a 'default' section hide it from ConfigParser
with open(edgerc_file, "r+") as myfile:
data = myfile.read().replace('default', '----DEFAULT----')
myfile.close()
with open(edgerc_file, "w") as myfile:
myfile.write(data)
myfile.close()

# Open the ~/.edgerc file for writing
config = ConfigParser()
config.read(edgerc_file)
configfile = open(edgerc_file, 'w')

# Remove a section that is being replaced
if replace_section:
print("--- Removing section: %s" % section_name_pretty)
print(f"--- Removing section: {section_name_pretty}")
config.remove_section(section_name)

# Add the new section
print("+++ Adding section: %s" % section_name_pretty)
print(f"+++ Adding section: {section_name_pretty}")
config.add_section(section_name)
config.set(section_name, 'client_secret', fields['Secret:'])
config.set(section_name, 'host', fields['URL:'].replace('https://', ''))
config.set(section_name, 'access_token', fields['Tokens:'])
config.set(section_name, 'client_token', fields['token:'])
config.set(section_name, 'max-body', '131072')
config.write(configfile)

configfile.close()
with open(edgerc_file, 'w') as configfile:
config.write(configfile)

# Undo the ConfigParser work around
with open(edgerc_file, "r") as myfile:
data = myfile.read().replace('----DEFAULT----', 'default')
myfile.close()
with open(edgerc_file, "w") as myfile:
myfile.write(data)
myfile.close()

print("\nDone. Please verify your credentials with the verify_creds.py script.\n")


if __name__ == "__main__":
Expand All @@ -166,4 +209,4 @@ def generate_edgerc(arguments, edgerc_file, enable_interruption):
This script will create a configuration section in the local ~/.edgerc credential file.
""")
generate_edgerc(args, "%s/.edgerc" % expanduser("~"), True)
generate_edgerc(args, f'{expanduser("~")}/.edgerc')
Loading

0 comments on commit a99370a

Please sign in to comment.