This commit is contained in:
Sylvain LE GAL 2022-03-25 12:26:50 +01:00
parent 33953ff3c7
commit d64140487f
9 changed files with 1412 additions and 87 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
env
__pycache__

View File

@ -1,92 +1,9 @@
# odoo-openupgrade-wizard # odoo-openupgrade-wizard
# TODO
## Getting started * restore ``# @click.version_option(version=ociedoo.__version__)`` when we know how
to avoid to duplicate information in ``pyproject.toml`` file and ``__init__.py`` file.
To make it easy for you to get started with GitLab, here's a list of recommended next steps. * move jinja2 templates files into dedicated files.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin https://gitlab.com/odoo-openupgrade-wizard/odoo-openupgrade-wizard.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://gitlab.com/odoo-openupgrade-wizard/odoo-openupgrade-wizard/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.

View File

View File

@ -0,0 +1,5 @@
"""Executed when module is run as a script."""
from odoo_openupgrade_wizard import cli
cli.main() # pylint: disable=no-value-for-parameter

View File

@ -0,0 +1,214 @@
import datetime
# import os
# import signal
# import subprocess
# import time
from pathlib import Path
from plumbum.cmd import mkdir
from jinja2 import Template
import time
import click
from loguru import logger
import odoo_openupgrade_wizard
from odoo_openupgrade_wizard.configuration_version_dependant import (
_get_odoo_version_str_list,
_get_odoo_versions,
)
from odoo_openupgrade_wizard.templates import (
_CONFIG_YML_TEMPLATE,
_REPO_YML_TEMPLATE,
_REQUIREMENTS_TXT_TEMPLATE,
_PRE_MIGRATION_SQL_TEMPLATE,
_POST_MIGRATION_PY_TEMPLATE,
)
# ############################################################################
# main()
# ############################################################################
@click.group(
short_help="Provide a wizard to simplify the use of OpenUpgrade.",
)
@click.option("-ef", "--env-folder", required=True,
type=click.Path(exists=True, dir_okay=True, file_okay=False, writable=True,
resolve_path=True))
@click.option("-fs", "--filestore-folder",
type=click.Path(dir_okay=True, file_okay=False,
resolve_path=True))
@click.pass_context
def main(ctx, env_folder, filestore_folder):
"""
TODO
"""
date_begin = datetime.datetime.now()
logger.debug("Beginning script '%s' ..." % (ctx.invoked_subcommand))
if not isinstance(ctx.obj, dict):
ctx.obj = {}
env_folder_path = Path(env_folder)
src_folder_path = env_folder_path / Path("./src/")
repo_folder_path = env_folder_path / Path("./repos/")
requirement_folder_path = env_folder_path / Path("./requirements/")
script_folder_path = env_folder_path / Path("./scripts/")
if not filestore_folder:
filestore_folder_path = env_folder_path / Path("./filestore/")
else:
filestore_folder_path = Path(filestore_folder)
config_file_path = env_folder_path / Path("config.yml")
# ###
# Handle log
# ###
log_folder_path = env_folder_path / Path("./log/")
# create log directory if not exists
if not log_folder_path.exists():
logger.info("Creating folder '%s' ..." % (log_folder_path))
mkdir(["--mode", "777", log_folder_path])
# Create log file
log_file_path = log_folder_path / Path("{}__{}.log".format(
date_begin.strftime("%Y_%m_%d__%H_%M_%S"), ctx.invoked_subcommand))
logger.add(log_file_path)
ctx.obj["env_folder_path"] = env_folder_path
ctx.obj["src_folder_path"] = src_folder_path
ctx.obj["repo_folder_path"] = repo_folder_path
ctx.obj["script_folder_path"] = script_folder_path
ctx.obj["filestore_folder_path"] = filestore_folder_path
ctx.obj["config_file_path"] = config_file_path
ctx.obj["requirement_folder_path"] = requirement_folder_path
# logger.info(ctx.obj)
# ############################################################################
# init()
# ############################################################################
@main.command(
short_help="Initialize OpenUpgrade Wizard Environment.",
)
@click.option("-iv", "--initial-version", required=True, prompt=True,
type=click.Choice(_get_odoo_version_str_list("initial")))
@click.option("-fv", "--final-version", required=True, prompt=True,
type=click.Choice(_get_odoo_version_str_list("final")))
@click.option("-er", "--extra-repository", "extra_repository_list",
# TODO, add a callback to check the quality of the argument
help="Coma separated extra repositories to use in the odoo environment."
"Ex: 'OCA/web,OCA/server-tools,GRAP/grap-odoo-incubator'")
@click.pass_context
def init(ctx, initial_version, final_version, extra_repository_list):
"""
TODO
"""
# 1. create src directory if not exists
if not ctx.obj["src_folder_path"].exists():
logger.info("Creating folder '%s' ..." % (ctx.obj["src_folder_path"]))
mkdir(["--mode", "777", ctx.obj["src_folder_path"]])
# 2. create filestore directory if not exists
if not ctx.obj["filestore_folder_path"].exists():
logger.info("Creating folder '%s' ..." % (ctx.obj["filestore_folder_path"]))
mkdir(["--mode", "777", ctx.obj["filestore_folder_path"]])
# 3. Create main config file
series = _get_odoo_versions(float(initial_version), float(final_version))
# Create initial first step
steps = [series[0].copy()]
steps[0].update({
"name": "step_1",
"action": "update",
"complete_name": "step_1__update__%s" % (steps[0]["version"]),
})
# Add all upgrade steps
count = 1
for serie in series[1:]:
steps.append(serie.copy())
steps[count].update({
"name": "step_%d" % (count+1),
"action": "upgrade",
"complete_name": "step_%d__upgrade__%s" % (count+1, serie["version"]),
})
count += 1
# add final update step
steps.append(series[-1].copy())
steps[-1].update({
"name": "step_%d" % (count + 1),
"action": "update",
"complete_name": "step_%d__update__%s" % (count+1, steps[-1]["version"]),
})
template = Template(_CONFIG_YML_TEMPLATE)
output = template.render(steps=steps)
with open(ctx.obj["config_file_path"], "w") as f:
logger.info("Creating configuration file '%s' ..." % (ctx.obj["config_file_path"]))
f.write(output)
f.close()
distinct_versions = list(set(x["version"] for x in series))
# 4. Create Repo folder and files
if not ctx.obj["repo_folder_path"].exists():
logger.info("Creating folder '%s' ..." % (ctx.obj["repo_folder_path"]))
mkdir([ctx.obj["repo_folder_path"]])
extra_repositories = extra_repository_list.split(",")
orgs = {x: [] for x in set([x.split("/")[0] for x in extra_repositories])}
for extra_repository in extra_repositories:
org, repo = extra_repository.split("/")
orgs[org].append(repo)
for version in distinct_versions:
template = Template(_REPO_YML_TEMPLATE)
output = template.render(version=version, orgs=orgs)
file_name =ctx.obj["repo_folder_path"] / Path("%s.yml" % (version))
with open(file_name, "w") as f:
logger.info("Creating Repo file '%s' ..." % (file_name))
f.write(output)
f.close()
# 5. Create Requirements folder and files
if not ctx.obj["requirement_folder_path"].exists():
logger.info("Creating folder '%s' ..." % (ctx.obj["requirement_folder_path"]))
mkdir([ctx.obj["requirement_folder_path"]])
for serie in series:
template = Template(_REQUIREMENTS_TXT_TEMPLATE)
output = template.render(python_libraries=serie["python_libraries"])
file_name =ctx.obj["requirement_folder_path"] / Path("%s_requirements.txt" % (serie["version"]))
with open(file_name, "w") as f:
logger.info("Creating Requirements file '%s' ..." % (file_name))
f.write(output)
f.close()
# 6. Create Scripts folder and files
if not ctx.obj["script_folder_path"].exists():
logger.info("Creating folder '%s' ..." % (ctx.obj["script_folder_path"]))
mkdir([ctx.obj["script_folder_path"]])
for step in steps:
step_path = ctx.obj["script_folder_path"] / step["complete_name"]
if not step_path.exists():
logger.info("Creating folder '%s' ..." % (step_path))
mkdir([step_path])
template = Template(_PRE_MIGRATION_SQL_TEMPLATE)
output = template.render()
file_name =step_path / Path("pre-migration.sql")
with open(file_name, "w") as f:
logger.info("Creating pre-migration.sql file '%s' ..." % (file_name))
f.write(output)
f.close()
template = Template(_POST_MIGRATION_PY_TEMPLATE)
output = template.render()
file_name =step_path / Path("post-migration.py")
with open(file_name, "w") as f:
logger.info("Creating post-migration.py file '%s' ..." % (file_name))
f.write(output)
f.close()

View File

@ -0,0 +1,31 @@
# List of the series of odoo
# python version is defined, based on the OCA CI.
# https://github.com/OCA/oca-addons-repo-template/blob/master/src/.github/workflows/%7B%25%20if%20ci%20%3D%3D%20'GitHub'%20%25%7Dtest.yml%7B%25%20endif%20%25%7D.jinja
_ODOO_SERIES = [
{"version": 6.0, "python": "python2.7", "python_libraries": ["openupgradelib"]},
{"version": 6.1, "python": "python2.7", "python_libraries": ["openupgradelib"]},
{"version": 7.0, "python": "python2.7", "python_libraries": ["openupgradelib"]},
{"version": 8.0, "python": "python2.7", "python_libraries": ["openupgradelib"]},
{"version": 9.0, "python": "python2.7", "python_libraries": ["openupgradelib"]},
{"version": 10.0, "python": "python2.7", "python_libraries": ["openupgradelib"]},
{"version": 11.0, "python": "python3.5", "python_libraries": ["openupgradelib"]},
{"version": 12.0, "python": "python3.6", "python_libraries": ["openupgradelib"]},
{"version": 13.0, "python": "python3.6", "python_libraries": ["openupgradelib"]},
{"version": 14.0, "python": "python3.6", "python_libraries": ["openupgradelib"]},
{"version": 15.0, "python": "python3.8", "python_libraries": ["openupgradelib"]},
]
def _get_odoo_version_str_list(mode):
serie_list = [x["version"] for x in _ODOO_SERIES]
if mode == "initial":
serie_list = serie_list[:-1]
if mode == "final":
serie_list = serie_list[1:]
return [str(x) for x in serie_list]
def _get_odoo_versions(initial, final):
result = []
for serie in _ODOO_SERIES:
if serie["version"] >= initial and serie["version"] <= final:
result.append(serie)
return result

View File

@ -0,0 +1,62 @@
_CONFIG_YML_TEMPLATE = """
migration_steps:
{% for step in steps %}
- name: {{ step['name'] }}
- complete_name: {{ step['complete_name'] }}
version: {{ step['version'] }}
action: {{ step['action'] }}
python: {{ step['python'] }}
{% endfor %}
"""
_REPO_YML_TEMPLATE = """
##############################################################################
## Odoo Repository
##############################################################################
./src/odoo:
remotes:
odoo: https://github.com/odoo/odoo
target: odoo {{ version }}-target
merges:
- odoo {{ version }}
##############################################################################
## OpenUpgrade Repository
##############################################################################
./src/openupgrade:
remotes:
OCA: https://github.com/OCA/OpenUpgrade
target: OCA {{ version }}-target
merges:
- OCA {{ version }}
{% for org_name, repo_list in orgs.items() %}
##############################################################################
## {{ org_name }} Repositories
##############################################################################
{% for repo in repo_list %}
./src/{{ org_name }}/{{ repo }}:
remotes:
{{ org_name }}: https://github.com/{{ org_name }}/{{ repo }}
target: {{ org_name }} {{ version }}-target
merges:
- {{ org_name }} {{ version }}
{% endfor %}
{% endfor %}
"""
_REQUIREMENTS_TXT_TEMPLATE = """
{%- for python_librairy in python_libraries -%}
{{ python_librairy }}
{% endfor %}
"""
_PRE_MIGRATION_SQL_TEMPLATE = ""
_POST_MIGRATION_PY_TEMPLATE = """
def main(self, step):
pass
"""

1032
poetry.lock generated Normal file

File diff suppressed because it is too large Load Diff

62
pyproject.toml Normal file
View File

@ -0,0 +1,62 @@
[tool.poetry]
name = "odoo-openupgrade-wizard"
version = "0.0.1"
description = "CLI tool to manage Odoo Major Upgrades"
authors = [
"GRAP, Groupement Régional Alimentaire de Proximité",
"Coop IT Easy SCRLfs",
]
maintainers = [
"Sylvain LE GAL",
]
license = "AGPLv3+"
readme = "README.md"
repository = "https://gitlab.com/odoo-openupgrade-wizard/odoo-openupgrade-wizard"
keywords = ["cli", "odoo", "openupgrade"]
classifiers = [
"Intended Audience :: Developers",
"Development Status :: 2 - Pre-Alpha",
"Operating System :: Unix",
"Programming Language :: Python :: 3",
"Framework :: Odoo",
]
[tool.poetry.scripts]
odoo-openupgrade-wizard = "odoo_openupgrade_wizard.cli:main"
[tool.poetry.dependencies]
python = "^3.5"
click = "^7.0"
loguru = "^0.6"
plumbum = "^1.7"
[tool.poetry.dev-dependencies]
pytest = [
{version = "<=6.1.2", python = "<3.10"},
{version = ">=6.2.5", python = ">=3.10"}
]
pytest-cov = "*"
safety = "*"
pylint = "*"
tox = "*"
towncrier = "*"
[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"
[tool.towncrier]
package = "ociedoo"
package_dir = "ociedoo"
filename = "CHANGES.rst"
directory = "newsfragments"
title_format = "{version} ({project_date})"
wrap = 72
[tool.black]
line-length = 79
[tool.isort]
profile = "black"
line_length = 79