diff --git a/.github/release-notes.md b/.github/release-notes.md index a8fef753..8181312e 100644 --- a/.github/release-notes.md +++ b/.github/release-notes.md @@ -1,3 +1,14 @@ +## Breaking changes + + + +- **The objects of the data model compare by value.** `a == b` is true for two objects of the same class with the same JSON (`serialize()`), also in the lists of the model (`in`, `count`, `remove`). It was true only for the same object: use `is` for that. `MoneroRpcConnection` compares the uri, the username, the password, the proxy uri, the zmq uri and the ssl verify. +- **The objects of the data model are not hashable.** `hash()` of one, putting it in a `set` or using it as a key of a `dict` raises `TypeError`: key them by what identifies them, as the hash of a tx, or by `id()`. +- **The raw RPC responses keep the types of their JSON**, in `send_json_request()` and the other raw requests of `MoneroRpcConnection`. A text stays a `str`, also when it looks like a number or a boolean, a large integer stays an `int` instead of becoming a `float`, `null` is `None`, and an empty list or object stays one. +- **Python 3.10 or later** is required: 3.8 and 3.9 are not supported anymore. +- **The macOS wheels need macOS 15 or later**: there is no wheel for macOS 14. +- **Type annotations:** `MoneroOutput.tx`, `MoneroTransfer.tx` and `MoneroRpcConnection.timeout_ms` can be `None`, and `MoneroTxQuery.include_outputs` is a `bool`: a type checker can report new errors. + ## Which file to download | Platform | File | diff --git a/.gitignore b/.gitignore index 619e16a5..ca41dafe 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,7 @@ !.vscode/launch.json !.vscode/tasks.json !.vscode/extensions.json +!.vscode/extensions/ !.vscode/.env /.env # made by bin/generate_typings.sh diff --git a/.vscode/extensions.json b/.vscode/extensions.json index bdf20adc..c75c7de4 100644 --- a/.vscode/extensions.json +++ b/.vscode/extensions.json @@ -13,7 +13,10 @@ "github.vscode-github-actions", "timonwong.shellcheck", "ryanluker.vscode-coverage-gutters", - "actboy168.tasks", - "ferrierbenjamin.fold-unfold-all-icone" + "ferrierbenjamin.fold-unfold-all-icone", + "compulim.indent4to2", + "kevinrose.vsc-python-indent", + "shardulm94.trailing-spaces", + "tamasfe.even-better-toml" ] } diff --git a/.vscode/extensions/status-bar-buttons/builds.js b/.vscode/extensions/status-bar-buttons/builds.js new file mode 100644 index 00000000..390ea221 --- /dev/null +++ b/.vscode/extensions/status-bar-buttons/builds.js @@ -0,0 +1,64 @@ +// The end of the builds of .vscode/tasks.json: a popup with the result and the time of the ones that failed or that were long, and the +// tests of the Testing panel read again after a build of the module, which they can not import while it is linked. + +const vscode = require('vscode'); + +const BUILD = /^build: /; +// the build of the module that the tests import +const MODULE = 'build: monero-python'; +// a shorter build that succeeds shows no popup, as the ones before each debug session +const LONG_MS = 30000; + +function formatTime(milliseconds) { + const seconds = Math.round(milliseconds / 1000); + return seconds < 60 ? `${seconds} s` : `${Math.floor(seconds / 60)} min ${seconds % 60} s`; +} + +function activate(context) { + // when each build started, by the name of its task + const starts = new Map(); + + function end(name, exitCode) { + const start = starts.get(name); + starts.delete(name); + // no exit code: the task was stopped + if (exitCode === undefined) { + return; + } + // not known for a build that started before a reload of the window + const time = start === undefined ? undefined : Date.now() - start; + if (exitCode !== 0) { + const after = time === undefined ? '' : ` after ${formatTime(time)}`; + vscode.window.showErrorMessage(`${name} failed${after}`, 'Show Terminal', 'Show Problems').then(choice => { + if (choice === 'Show Terminal') { + vscode.commands.executeCommand('workbench.action.terminal.focus'); + } else if (choice === 'Show Problems') { + vscode.commands.executeCommand('workbench.actions.view.problems'); + } + }); + return; + } + if (name === MODULE) { + vscode.commands.executeCommand('testing.refreshTests'); + } + if (time === undefined || time >= LONG_MS) { + const took = time === undefined ? '' : ` in ${formatTime(time)}`; + vscode.window.showInformationMessage(`${name} succeeded${took}`); + } + } + + context.subscriptions.push( + vscode.tasks.onDidStartTask(event => { + if (BUILD.test(event.execution.task.name)) { + starts.set(event.execution.task.name, Date.now()); + } + }), + vscode.tasks.onDidEndTaskProcess(event => { + if (BUILD.test(event.execution.task.name)) { + end(event.execution.task.name, event.exitCode); + } + }), + ); +} + +module.exports = { activate }; diff --git a/.vscode/extensions/status-bar-buttons/button.js b/.vscode/extensions/status-bar-buttons/button.js new file mode 100644 index 00000000..3d11c79b --- /dev/null +++ b/.vscode/extensions/status-bar-buttons/button.js @@ -0,0 +1,21 @@ +// A button of the status bar that can wait for the task of another one. + +const vscode = require('vscode'); + +// the higher the priority, the more to the left +function createButton(context, priority, name) { + const item = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left, priority); + item.name = name; + context.subscriptions.push(item); + + return function show({ text, tooltip, command, waitsFor }) { + item.text = text; + item.tooltip = waitsFor ? `Waits for "${waitsFor}" to end` : tooltip; + // a button that waits is gray, and a click on it does nothing + item.color = waitsFor ? new vscode.ThemeColor('disabledForeground') : undefined; + item.command = waitsFor ? undefined : command; + item.show(); + }; +} + +module.exports = { createButton }; diff --git a/.vscode/extensions/status-bar-buttons/docker.js b/.vscode/extensions/status-bar-buttons/docker.js new file mode 100644 index 00000000..ff876a91 --- /dev/null +++ b/.vscode/extensions/status-bar-buttons/docker.js @@ -0,0 +1,100 @@ +// The button of the network of the integration tests: "Setup Docker" when it is down, "Stop Docker" when it is up, with a warning icon +// when some of its services do not run. The commands are the ones of the tasks of .vscode/tasks.json, which the button runs. + +const childProcess = require('child_process'); +const vscode = require('vscode'); +const { createButton } = require('./button'); +const running = require('./running'); + +const SETUP = { + task: 'tests: setup docker', + label: 'Setup Docker', + icon: 'play', + tooltip: 'setup docker environment for integration tests', +}; +const STOP = { + task: 'tests: stop docker', + label: 'Stop Docker', + icon: 'stop-circle', + tooltip: 'stop the Docker environment for integration tests', +}; +const COMMAND = 'moneroPython.runDockerTask'; +// the services that the task of the setup starts +const SERVICES = ['node_1', 'node_2', 'xmr_wallet_1', 'xmr_wallet_2', 'xmr_wallet_3']; +// the names of the services that run, one for each line +const PS_ARGS = ['compose', '-f', 'tests/docker-compose.yml', 'ps', '--services', '--status', 'running']; +// between two checks, while the window has the focus. A check is a process that ends on its own: one that waits for the events of docker +// would stay when the extensions of VS Code crash +const CHECK_MS = 5000; +// a check that does not answer is given up +const TIMEOUT_MS = 10000; + +function activate(context) { + const cwd = vscode.workspace.workspaceFolders[0].uri.fsPath; + const show = createButton(context, 50.3, 'Docker Test Network'); + let shown = SETUP; + // the services that run + let services = []; + let checks = 0; + let pending = 0; + let disposed = false; + + function render() { + // while one of the two tasks runs, its button stays, with a spinning icon + const busy = [SETUP, STOP].find(button => running.isRunning(button.task)); + shown = busy || (services.length > 0 ? STOP : SETUP); + const missing = SERVICES.filter(service => !services.includes(service)); + const partial = !busy && shown === STOP && missing.length > 0; + const icon = busy ? 'sync~spin' : partial ? 'warning' : shown.icon; + show({ + text: `$(${icon}) ${shown.label}`, + tooltip: partial ? `Not running: ${missing.join(', ')}. Click to ${shown.tooltip}` : shown.tooltip, + command: COMMAND, + waitsFor: busy ? undefined : running.blocker([SETUP.task, STOP.task]), + }); + } + + function check() { + const current = ++checks; + pending++; + childProcess.execFile('docker', PS_ARGS, { cwd, timeout: TIMEOUT_MS }, (error, stdout) => { + pending--; + // an older check that ends late does not replace the result of a newer one + if (disposed || current !== checks) { + return; + } + // without docker the button is the one of the setup, whose task says what is wrong + services = error ? [] : stdout.split('\n').map(line => line.trim()).filter(Boolean); + render(); + }); + } + + // for the changes made from a terminal + const timer = setInterval(() => { + if (vscode.window.state.focused && pending === 0) { + check(); + } + }, CHECK_MS); + + running.onChange(render); + context.subscriptions.push( + vscode.commands.registerCommand(COMMAND, () => vscode.commands.executeCommand('workbench.action.tasks.runTask', shown.task)), + vscode.tasks.onDidEndTask(() => check()), + vscode.window.onDidChangeWindowState(state => { + if (state.focused) { + check(); + } + }), + { + dispose() { + disposed = true; + clearInterval(timer); + }, + }, + ); + + render(); + check(); +} + +module.exports = { activate, SERVICES }; diff --git a/.vscode/extensions/status-bar-buttons/docs.js b/.vscode/extensions/status-bar-buttons/docs.js new file mode 100644 index 00000000..2c80c748 --- /dev/null +++ b/.vscode/extensions/status-bar-buttons/docs.js @@ -0,0 +1,103 @@ +// The button of the docs: "Build Docs" runs the task "docs: serve" of .vscode/tasks.json, with a spinning icon while the site is +// built and "Stop Docs" once it is served. A click while the task runs stops it. The other buttons wait while the site is built, not +// while it is served. + +const net = require('net'); +const vscode = require('vscode'); +const { createButton } = require('./button'); +const running = require('./running'); + +const TASK = 'docs: serve'; +// the address of mkdocs serve, which listens on it only once the site is built +const HOST = '127.0.0.1'; +const PORT = 8000; +const URL = `http://${HOST}:${PORT}`; +const COMMAND = 'moneroPython.toggleDocs'; +// between two checks of the address while the site is built +const CHECK_MS = 1000; + +function activate(context) { + const show = createButton(context, 50.2, 'Docs'); + const executions = () => vscode.tasks.taskExecutions.filter(execution => execution.task.name === TASK); + let served = false; + let socket; + let checkTimer; + + function render() { + if (!running.isRunning(TASK)) { + show({ + text: '$(book) Build Docs', + tooltip: `Build and serve the docs at ${URL}`, + command: COMMAND, + waitsFor: running.blocker([TASK]), + }); + } else if (!served) { + show({ text: '$(sync~spin) Building Docs', tooltip: 'Building the docs, click to stop', command: COMMAND }); + } else { + const tooltip = new vscode.MarkdownString(`The docs are at [${URL}](${URL}), click to stop`); + show({ text: '$(stop-circle) Stop Docs', tooltip, command: COMMAND }); + } + } + + function stopChecking() { + clearTimeout(checkTimer); + if (socket) { + socket.removeAllListeners(); + // an error of a connection that is given up is of no use + socket.on('error', () => {}); + socket.destroy(); + socket = undefined; + } + } + + // tries to connect to the address until it answers, which is when the build ended + function check() { + socket = net.connect(PORT, HOST); + socket.once('connect', () => { + stopChecking(); + served = true; + // which renders the buttons again + running.setIdle(TASK); + }); + socket.once('error', () => { + checkTimer = setTimeout(check, CHECK_MS); + }); + } + + // at the start and at the end of the task + function restart() { + stopChecking(); + served = false; + render(); + if (running.isRunning(TASK)) { + check(); + } + } + + running.onChange(render); + context.subscriptions.push( + vscode.commands.registerCommand(COMMAND, () => { + if (running.isRunning(TASK)) { + executions().forEach(execution => execution.terminate()); + } else { + vscode.commands.executeCommand('workbench.action.tasks.runTask', TASK); + } + }), + vscode.tasks.onDidStartTask(event => { + if (event.execution.task.name === TASK) { + restart(); + } + }), + vscode.tasks.onDidEndTask(event => { + if (event.execution.task.name === TASK) { + restart(); + } + }), + { dispose: stopChecking }, + ); + + // the task may run already, after a reload of the window + restart(); +} + +module.exports = { activate }; diff --git a/.vscode/extensions/status-bar-buttons/extension.js b/.vscode/extensions/status-bar-buttons/extension.js new file mode 100644 index 00000000..ca77055d --- /dev/null +++ b/.vscode/extensions/status-bar-buttons/extension.js @@ -0,0 +1,21 @@ +// The buttons of the status bar of the tasks of .vscode/tasks.json, which wait for each other and change with the state of what their +// task starts, the menu of the lint, the popups of the problems that a task found and of the end of the builds, and the refresh of the tests after one. + +const builds = require('./builds'); +const docker = require('./docker'); +const docs = require('./docs'); +const lint = require('./lint'); +const running = require('./running'); +const tasks = require('./tasks'); + +function activate(context) { + // first: the buttons ask it what runs + running.activate(context); + tasks.activate(context); + docker.activate(context); + docs.activate(context); + lint.activate(context); + builds.activate(context); +} + +module.exports = { activate }; diff --git a/.vscode/extensions/status-bar-buttons/lint.js b/.vscode/extensions/status-bar-buttons/lint.js new file mode 100644 index 00000000..51f2f390 --- /dev/null +++ b/.vscode/extensions/status-bar-buttons/lint.js @@ -0,0 +1,180 @@ +// The button "Lint", whose menu runs one of the lint tasks of .vscode/tasks.json, and the popups of them: when one ends, one for each +// of the first problems that its problem matcher found, with a button that opens it, and one for the others. The check of the links +// also has one for its redirects and one for each hint of lychee. + +const vscode = require('vscode'); +const { createButton } = require('./button'); +const running = require('./running'); + +// "sources" are the "source" of the problem matchers of a task, which tell its problems from the others +const LINTS = [ + { + task: 'lint: links', + name: 'Links', + icon: 'link', + description: 'the links to the web of the docs, the stubs and README.md', + sources: ['lychee'], + // the copy of the output that the task writes, in the folder of the workspace + log: ['.cache', 'lint-links.log'], + }, + { + task: 'lint: spelling', + name: 'Spelling', + icon: 'whole-word', + description: 'codespell on the files of git', + sources: ['codespell'], + }, + { + task: 'lint: workflows', + name: 'Workflows', + icon: 'github-action', + description: 'actionlint and zizmor on .github', + sources: ['actionlint', 'zizmor'], + }, + { + task: 'lint: examples', + name: 'Examples', + icon: 'code', + description: 'the code of the docs and of README.md against the stubs', + sources: ['check_examples'], + }, +]; +const COMMAND = 'moneroPython.lint'; +// a line of lychee about the whole check +const HINT = /^Hint: (.+)$/gm; +// the count of the redirects in the last line of the report: with -vv, their details are lines of the output +const REDIRECTS = /(\d+) Redirects\b/; +// the colors of a terminal +const ANSI = /\u001b\[[0-9;]*m/g; +// the popups of single problems, VS Code hides the ones that are too many +const MAX_POPUPS = 3; +// the problems of the matcher reach the extensions a moment after the end of the task +const WAIT_MS = 1000; + +function findProblems(sources) { + return vscode.languages.getDiagnostics().flatMap(([uri, diagnostics]) => + diagnostics.filter(diagnostic => sources.includes(diagnostic.source)).map(diagnostic => ({ uri, diagnostic }))); +} + +function popup(isError, message, button, action) { + const show = isError ? vscode.window.showErrorMessage : vscode.window.showWarningMessage; + show(message, button).then(choice => { + if (choice === button) { + action(); + } + }); +} + +const isError = problem => problem.diagnostic.severity === vscode.DiagnosticSeverity.Error; + +const showTerminal = () => vscode.commands.executeCommand('workbench.action.terminal.focus'); + +// the warnings about the whole check, from the copy of the output +async function findWarnings(log) { + const file = vscode.Uri.joinPath(vscode.workspace.workspaceFolders[0].uri, ...log); + try { + const output = Buffer.from(await vscode.workspace.fs.readFile(file)).toString('utf8').replace(ANSI, ''); + const warnings = Array.from(output.matchAll(HINT), match => match[1].trim()); + const redirects = Number(REDIRECTS.exec(output)?.[1] ?? 0); + if (redirects > 0) { + warnings.unshift(`${redirects} redirect${redirects === 1 ? '' : 's'}, the terminal shows where they go`); + } + return warnings; + } catch { + // no copy of the output: no warnings + return []; + } +} + +async function reportWarnings(title, log, exitCode) { + // no exit code: the task was stopped, and the copy is not whole + if (log && exitCode !== undefined) { + for (const warning of await findWarnings(log)) { + popup(false, `${title}: ${warning}`, 'Show Terminal', showTerminal); + } + } +} + +function reportProblems(title, sources, exitCode) { + // errors first. A check that passes has none: the ones that are there are old, as the ones of "docs: build", which checks the + // examples too + const problems = findProblems(sources) + .filter(problem => exitCode !== 0 || !isError(problem)) + .sort((a, b) => a.diagnostic.severity - b.diagnostic.severity); + if (problems.length === 0) { + // no exit code: the task was stopped. Another one than 0 without problems: the check did not run, as without a network + if (exitCode !== undefined && exitCode !== 0) { + popup(true, `${title} failed with exit code ${exitCode}`, 'Show Terminal', showTerminal); + } + return; + } + for (const problem of problems.slice(0, MAX_POPUPS)) { + const { uri, diagnostic } = problem; + const where = `${vscode.workspace.asRelativePath(uri)}:${diagnostic.range.start.line + 1}`; + popup(isError(problem), `${title}: ${diagnostic.message} (${where})`, 'Open', + () => vscode.window.showTextDocument(uri, { selection: diagnostic.range })); + } + const others = problems.slice(MAX_POPUPS); + if (others.length > 0) { + popup(others.some(isError), `${title}: ${others.length} more, ${problems.length} in all`, 'Show Problems', + () => vscode.commands.executeCommand('workbench.actions.view.problems')); + } +} + +function report({ name, sources, log }, exitCode) { + const title = `Lint ${name}`; + reportProblems(title, sources, exitCode); + return reportWarnings(title, log, exitCode); +} + +const runTask = task => vscode.commands.executeCommand('workbench.action.tasks.runTask', task); + +async function choose() { + const items = LINTS.map(lint => ({ label: `$(${lint.icon}) ${lint.name}`, description: lint.description, task: lint.task })); + const choice = await vscode.window.showQuickPick(items, { placeHolder: 'What to check' }); + if (!choice) { + return; + } + // a task may have started while the menu was open + const blocker = running.blocker(LINTS.map(lint => lint.task)); + if (blocker) { + vscode.window.showWarningMessage(`Lint waits for "${blocker}" to end`); + return; + } + runTask(choice.task); +} + +function createLintButton(context) { + const show = createButton(context, 50.1, 'Lint'); + const render = () => { + const busy = LINTS.find(lint => running.isRunning(lint.task)); + show({ + text: busy ? `$(sync~spin) Lint ${busy.name}` : '$(checklist) Lint', + tooltip: busy ? busy.description : 'check the links, the spelling, the workflows or the examples', + // while one runs, as the other buttons: VS Code asks whether to stop it + command: busy ? { title: 'Lint', command: 'workbench.action.tasks.runTask', arguments: [busy.task] } : COMMAND, + waitsFor: busy ? undefined : running.blocker(LINTS.map(lint => lint.task)), + }); + }; + running.onChange(render); + context.subscriptions.push(vscode.commands.registerCommand(COMMAND, choose)); + render(); +} + +function activate(context) { + createLintButton(context); + // one for each task, as two of them can run from "Run Task" + const timers = new Map(); + context.subscriptions.push( + vscode.tasks.onDidEndTaskProcess(event => { + const lint = LINTS.find(lint => lint.task === event.execution.task.name); + if (lint) { + clearTimeout(timers.get(lint.task)); + timers.set(lint.task, setTimeout(report, WAIT_MS, lint, event.exitCode)); + } + }), + { dispose: () => timers.forEach(clearTimeout) }, + ); +} + +module.exports = { activate }; diff --git a/.vscode/extensions/status-bar-buttons/package.json b/.vscode/extensions/status-bar-buttons/package.json new file mode 100644 index 00000000..0db1af4b --- /dev/null +++ b/.vscode/extensions/status-bar-buttons/package.json @@ -0,0 +1,12 @@ +{ + "name": "status-bar-buttons", + "displayName": "monero-python: status bar buttons", + "description": "Buttons of the status bar that wait for each other: build, docker network of the tests, docs and check of the links, with popups of what they find and of the end of the builds", + "publisher": "libmonero", + "version": "0.0.1", + "private": true, + "engines": { "vscode": "^1.89.0" }, + "main": "./extension.js", + "activationEvents": ["workspaceContains:tests/docker-compose.yml"], + "extensionKind": ["workspace"] +} diff --git a/.vscode/extensions/status-bar-buttons/running.js b/.vscode/extensions/status-bar-buttons/running.js new file mode 100644 index 00000000..d77ee37b --- /dev/null +++ b/.vscode/extensions/status-bar-buttons/running.js @@ -0,0 +1,46 @@ +// The tasks of .vscode/tasks.json that run, which the buttons share: while one runs, the buttons of the others wait, so that two of +// them do not work at once, as a build while the tests use the module. + +const vscode = require('vscode'); + +// the names of the tasks that run +const running = new Set(); +// the ones of them that make no button wait, as the server of the docs once it serves them +const idle = new Set(); +const listeners = []; + +// not the tasks that the extensions make +const isOfWorkspace = execution => execution.task.source === 'Workspace'; + +function activate(context) { + const change = (event, apply) => { + if (isOfWorkspace(event.execution)) { + apply(event.execution.task.name); + listeners.forEach(listener => listener()); + } + }; + // before the subscriptions of the buttons: their listeners of the same events find the tasks up to date + context.subscriptions.push( + vscode.tasks.onDidStartTask(event => change(event, name => running.add(name))), + vscode.tasks.onDidEndTask(event => change(event, name => { + running.delete(name); + idle.delete(name); + })), + ); + // the ones that run already, after a reload of the window + vscode.tasks.taskExecutions.filter(isOfWorkspace).forEach(execution => running.add(execution.task.name)); +} + +const isRunning = name => running.has(name); + +// the task that a button waits for, if any: one that runs, is not idle and is not one of the tasks of the button +const blocker = own => [...running].find(name => !idle.has(name) && !own.includes(name)); + +function setIdle(name) { + idle.add(name); + listeners.forEach(listener => listener()); +} + +const onChange = listener => listeners.push(listener); + +module.exports = { activate, isRunning, blocker, setIdle, onChange }; diff --git a/.vscode/extensions/status-bar-buttons/tasks.js b/.vscode/extensions/status-bar-buttons/tasks.js new file mode 100644 index 00000000..d71d169b --- /dev/null +++ b/.vscode/extensions/status-bar-buttons/tasks.js @@ -0,0 +1,28 @@ +// The buttons that only run a task of .vscode/tasks.json, with a spinning icon while it runs. + +const { createButton } = require('./button'); +const running = require('./running'); + +const BUTTONS = [ + { task: 'build: monero-python', label: 'Build', icon: 'gear', tooltip: 'build monero-python', priority: 50.4 }, +]; + +function activate(context) { + for (const { task, label, icon, tooltip, priority } of BUTTONS) { + const show = createButton(context, priority, label); + const command = { title: label, command: 'workbench.action.tasks.runTask', arguments: [task] }; + const render = () => { + const busy = running.isRunning(task); + show({ + text: `$(${busy ? 'sync~spin' : icon}) ${label}`, + tooltip, + command, + waitsFor: busy ? undefined : running.blocker([task]), + }); + }; + running.onChange(render); + render(); + } +} + +module.exports = { activate }; diff --git a/.vscode/settings.json b/.vscode/settings.json index 93e8cef1..21974c21 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -74,7 +74,7 @@ "files.trimTrailingWhitespace": true, "files.insertFinalNewline": true, - // the extension Tasks shows on the status bar only the tasks that ask for it in tasks.json (options.statusbar.hide: false); its "..." - // button lists all of them + // the buttons of the status bar are of .vscode/extensions/status-bar-buttons: who has the extension Tasks installed too would see a + // button for each task without this "tasks.statusbar.default.hide": true } diff --git a/.vscode/tasks.json b/.vscode/tasks.json index b17164a3..af81a1b6 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -17,37 +17,31 @@ "problemMatcher": [] }, { - // monero-project and monero-cpp, once and after an update of the submodules; JOBS=3 because a compiler of monero - // takes up to 1.5 GB of memory + // monero-project and monero-cpp, once and after an update of the submodules. + // The builds run MONERO_JOBS compilers at once, 3 by default because one of monero takes up to 1.5 GB of memory, and at a + // low priority (nice), so the machine stays usable. On Windows, where these commands are not, they are the plain ones "label": "build: monero-cpp", "type": "shell", - "command": "./bin/build_monero_cpp.sh", - "options": { "env": { "JOBS": "3" } }, + "command": "JOBS=\"$(printenv MONERO_JOBS | grep . || echo 3)\" nice -n 19 ./bin/build_monero_cpp.sh", + "windows": { "command": "./bin/build_monero_cpp.sh" }, "problemMatcher": ["$gcc"] }, { "label": "build: monero-python", "detail": "build monero-python", "type": "shell", - "command": "cmake -B build -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -Dpybind11_DIR=\"$(python3 -m pybind11 --cmakedir)\" && cmake --build build -j3", + "command": "cmake -B build -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -Dpybind11_DIR=\"$(python3 -m pybind11 --cmakedir)\" && nice -n 19 cmake --build build -j\"$(printenv MONERO_JOBS | grep . || echo 3)\"", + "windows": { "command": "cmake -B build -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -Dpybind11_DIR=\"$(python3 -m pybind11 --cmakedir)\" && cmake --build build -j3" }, "group": { "kind": "build", "isDefault": true }, - "problemMatcher": ["$gcc"], - "options": { - "statusbar": { - "hide": false, - "label": "Build", - "detail": "build monero-python", - "icon": { "id": "gear" }, - // while it runs, a spinning icon - "running": { "icon": { "id": "sync~spin" } } - } - } + // its button of the status bar, as the other ones, is of .vscode/extensions/status-bar-buttons + "problemMatcher": ["$gcc"] }, { // the module with the symbols and no optimization, for the debugger of C++, in a folder of its own "label": "build: monero-python module (debug)", "type": "shell", - "command": "cmake -B build-debug -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -Dpybind11_DIR=\"$(python3 -m pybind11 --cmakedir)\" && cmake --build build-debug -j3", + "command": "cmake -B build-debug -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -Dpybind11_DIR=\"$(python3 -m pybind11 --cmakedir)\" && nice -n 19 cmake --build build-debug -j\"$(printenv MONERO_JOBS | grep . || echo 3)\"", + "windows": { "command": "cmake -B build-debug -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -Dpybind11_DIR=\"$(python3 -m pybind11 --cmakedir)\" && cmake --build build-debug -j3" }, "problemMatcher": ["$gcc"] }, { @@ -55,7 +49,8 @@ // build. The type stays in the cache of that build, also for bin/build_monero_cpp.sh: -DCMAKE_BUILD_TYPE= goes back "label": "build: monero-cpp with debug info", "type": "shell", - "command": "cmake -S external/monero-cpp -B external/monero-cpp/build -DCMAKE_BUILD_TYPE=RelWithDebInfo && cmake --build external/monero-cpp/build -j3", + "command": "cmake -S external/monero-cpp -B external/monero-cpp/build -DCMAKE_BUILD_TYPE=RelWithDebInfo && nice -n 19 cmake --build external/monero-cpp/build -j\"$(printenv MONERO_JOBS | grep . || echo 3)\"", + "windows": { "command": "cmake -S external/monero-cpp -B external/monero-cpp/build -DCMAKE_BUILD_TYPE=RelWithDebInfo && cmake --build external/monero-cpp/build -j3" }, "problemMatcher": ["$gcc"] }, { @@ -123,43 +118,47 @@ } }, { + // this and "tests: stop docker" share a button of the status bar, which shows one of the two by the state of docker: the + // extension of .vscode/extensions/status-bar-buttons + // the services of this command are the SERVICES of the button, in docker.js of that extension "label": "tests: setup docker", "type": "shell", "command": "docker compose -f tests/docker-compose.yml up -d node_1 node_2 xmr_wallet_1 xmr_wallet_2 xmr_wallet_3", - "problemMatcher": [], - "options": { - "statusbar": { - "hide": false, - "label": "Setup Docker", - "detail": "setup docker environment for integration tests", - "icon": { "id": "play" }, - // while it runs, a spinning icon - "running": { "icon": { "id": "sync~spin" } } - } - } + "problemMatcher": [] }, { "label": "tests: stop docker", "type": "shell", "command": "docker compose -f tests/docker-compose.yml down -v", - "problemMatcher": [], - "options": { - "statusbar": { - "hide": false, - "label": "Stop Docker", - "detail": "stop the Docker environment for integration tests", - "icon": { "id": "stop-circle" }, - // while it runs, a spinning icon - "running": { "icon": { "id": "sync~spin" } } - } - } + "problemMatcher": [] }, { // actionlint and zizmor, with the versions of .github/workflows/lint-workflows.yml "label": "lint: workflows", "type": "shell", "command": "./bin/lint_workflows.sh", - "problemMatcher": [] + // the links of zizmor in the names of its rules would be in the lines that the matcher reads + "options": { "env": { "ZIZMOR_RENDER_LINKS": "never" } }, + // each finding is a problem of Problems, at its line + "problemMatcher": [ + { + "owner": "actionlint", + "source": "actionlint", + "fileLocation": ["relative", "${workspaceFolder}"], + "severity": "error", + "pattern": { "regexp": "^(\\.github/.+\\.ya?ml):(\\d+):(\\d+): (.+)$", "file": 1, "line": 2, "column": 3, "message": 4 } + }, + { + "owner": "zizmor", + "source": "zizmor", + "fileLocation": ["relative", "${workspaceFolder}"], + "severity": "info", + "pattern": [ + { "regexp": "^(error|warning|info|help)\\[([^\\]]+)\\]: (.+)$", "severity": 1, "code": 2, "message": 3 }, + { "regexp": "^\\s*--> (.+):(\\d+):(\\d+)$", "file": 1, "line": 2, "column": 3 } + ] + } + ] }, { // codespell on the files of git, with the version of .github/workflows/spelling.yml @@ -168,49 +167,79 @@ "command": "./bin/check_spelling.sh", "problemMatcher": { "owner": "codespell", + "source": "codespell", "fileLocation": ["relative", "${workspaceFolder}"], "pattern": { "regexp": "^(.+):(\\d+): (.+)$", "file": 1, "line": 2, "message": 3 } } }, { + // the code of the docs and of README.md against the stubs, the first step of "docs: build" + "label": "lint: examples", + "type": "shell", + "command": "./bin/docs.sh check", + "problemMatcher": { + "owner": "check_examples", + "source": "check_examples", + "fileLocation": ["relative", "${workspaceFolder}"], + "pattern": { + "regexp": "^(.+\\.md):(\\d+):(\\d+): (error|warning|information): (.+)$", + "file": 1, + "line": 2, + "column": 3, + "severity": 4, + "message": 5 + } + } + }, + { + // its button of the status bar, which stops it once the docs are served, is of .vscode/extensions/status-bar-buttons "label": "docs: serve", "type": "shell", "command": "./bin/docs.sh serve", "isBackground": true, - "problemMatcher": [], - "options": { - "statusbar": { - "hide": false, - "label": "$(book) Build Docs", - "detail": "Build and serve the docs at http://127.0.0.1:8000", - "running": { "label": "$(sync~spin) Docs at http://127.0.0.1:8000" } + // the warnings of mkdocs in Problems, again at every build of the site + "problemMatcher": [ + { + "owner": "mkdocs", + "source": "mkdocs", + "severity": "warning", + "fileLocation": ["relative", "${workspaceFolder}/docs/mkdocs/docs"], + "pattern": { + "kind": "file", + "regexp": "^WARNING\\s+-\\s+(?:Doc file '|mkdocs_autorefs: )([^':]+\\.md)(?:'|:) (.+)$", + "file": 1, + "message": 2 + }, + "background": { "activeOnStart": true, "beginsPattern": "Building documentation", "endsPattern": "Documentation built in" } + }, + { + "owner": "mkdocs-docstrings", + "source": "mkdocs", + "severity": "warning", + "fileLocation": "absolute", + "pattern": { "regexp": "^WARNING\\s+-\\s+griffe: (.+\\.pyi?):(\\d+): (.+)$", "file": 1, "line": 2, "message": 3 }, + "background": { "activeOnStart": true, "beginsPattern": "Building documentation", "endsPattern": "Documentation built in" } } - } + ] }, { // lychee on the links to the web of the docs, the stubs and README.md, with the version of .github/workflows/links.yml "label": "lint: links", "type": "shell", - "command": "./bin/check_links.sh", - // each broken link is an error of Problems, at its line + // -vv shows where each redirect goes, and a line for each link too: grep leaves out the ones that were excluded, the ones + // that are fine and the debug. tee keeps a copy of the output for the popups, and pipefail the exit code of the check + "command": "set -o pipefail; mkdir -p .cache && ./bin/check_links.sh -vv 2>&1 | tee .cache/lint-links.log | grep -v -E '^\\[EXCLUDED\\]|^ *\\[DEBUG\\]|^ *\\[200\\] [^|]*$'", + // each broken link is an error of Problems, at its line, and a popup of .vscode/extensions/status-bar-buttons, which finds + // them by their "source" "problemMatcher": { "owner": "lychee", + "source": "lychee", "fileLocation": ["relative", "${workspaceFolder}"], "severity": "error", "pattern": [ { "regexp": "^\\[(.+)\\]:$", "file": 1 }, - { "regexp": "^\\s+(\\[\\w+\\] \\S+) \\(at (\\d+):(\\d+)\\)", "message": 1, "line": 2, "column": 3, "loop": true } + { "regexp": "^\\s*(\\[\\w+\\] \\S+) \\(at (\\d+):(\\d+)\\)", "message": 1, "line": 2, "column": 3, "loop": true } ] - }, - "options": { - "statusbar": { - "hide": false, - "label": "Lint Docs", - "detail": "Lint documentation links", - "icon": { "id": "checklist" }, - // while it runs, a spinning icon - "running": { "icon": { "id": "sync~spin" } } - } } }, { @@ -218,7 +247,41 @@ "label": "docs: build", "type": "shell", "command": "./bin/docs.sh build", - "problemMatcher": [] + // in Problems, the errors of the code of the examples (bin/check_examples.py) and the warnings of mkdocs + "problemMatcher": [ + { + "owner": "check_examples", + "source": "check_examples", + "fileLocation": ["relative", "${workspaceFolder}"], + "pattern": { + "regexp": "^(.+\\.md):(\\d+):(\\d+): (error|warning|information): (.+)$", + "file": 1, + "line": 2, + "column": 3, + "severity": 4, + "message": 5 + } + }, + { + "owner": "mkdocs", + "source": "mkdocs", + "severity": "warning", + "fileLocation": ["relative", "${workspaceFolder}/docs/mkdocs/docs"], + "pattern": { + "kind": "file", + "regexp": "^WARNING\\s+-\\s+(?:Doc file '|mkdocs_autorefs: )([^':]+\\.md)(?:'|:) (.+)$", + "file": 1, + "message": 2 + } + }, + { + "owner": "mkdocs-docstrings", + "source": "mkdocs", + "severity": "warning", + "fileLocation": "absolute", + "pattern": { "regexp": "^WARNING\\s+-\\s+griffe: (.+\\.pyi?):(\\d+): (.+)$", "file": 1, "line": 2, "message": 3 } + } + ] } ] } diff --git a/README.md b/README.md index 03d17b78..9d4c399a 100644 --- a/README.md +++ b/README.md @@ -115,11 +115,11 @@ Every [release](https://github.com/libmonero/monero-python/releases) has prebuil * Debian and Ubuntu: `python3-monero_-11_.deb` for `bookworm`, `trixie`, `jammy` and `noble` on `amd64`, `arm64` and `armhf`, installed for the system Python 3: ```bash - sudo apt install ./python3-monero_0.9.11-1noble1_amd64.deb + sudo apt install ./python3-monero_0.9.13-1noble1_amd64.deb ``` * macOS and Windows: one wheel per Python version, `monero---.whl`: ```bash - pip3 install monero-0.9.11-cp313-cp313-win_amd64.whl + pip3 install monero-0.9.13-cp313-cp313-win_amd64.whl ``` On anything else, build it from source. diff --git a/bin/build_libmonero_python.sh b/bin/build_libmonero_python.sh index 3572013d..9b83cd83 100755 --- a/bin/build_libmonero_python.sh +++ b/bin/build_libmonero_python.sh @@ -1,65 +1,24 @@ #!/usr/bin/env bash +# Builds monero-project, monero-cpp and the module. JOBS is the number of compilers at once for the module, and for monero-project +# on Linux and macOS, 3 by default +set -euo pipefail -# ccache for the compilations when it is installed, the plain build otherwise. monero-project and the module look for it themselves -# (USE_CCACHE in their CMakeLists.txt), monero-cpp has to be told to use it -CMAKE_CCACHE_ARGS=() -if command -v ccache > /dev/null 2>&1; then - echo "Using ccache: $(command -v ccache)" - CMAKE_CCACHE_ARGS=(-DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache) -fi +root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) -# build monero-project dependencies -cd ./external/monero-cpp/external/monero-project/ || exit 1 -git submodule update --init --force || exit 1 -HOST_NCORES=$(nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null || echo 1) -if [[ $(uname -s) == "MINGW64_NT"* || $(uname -s) == "MSYS"* ]]; then - bit=$(getconf LONG_BIT) - FOLDER=$(cd "${MINGW_PREFIX}"/.. && pwd -W) - if [ "$bit" == "64" ]; then - cmake -G "MSYS Makefiles" \ - -D STATIC=ON \ - -D ARCH="x86-64" \ - -D BUILD_64=ON \ - -D CMAKE_BUILD_TYPE=Release \ - -D BUILD_TAG="win-x64" \ - -D CMAKE_TOOLCHAIN_FILE=../../cmake/64-bit-toolchain.cmake \ - -D MSYS2_FOLDER="$FOLDER" \ - ../../ - - make -j"$HOST_NCORES" wallet cryptonote_protocol || exit 1 - else - cmake -G "MSYS Makefiles" \ - -D STATIC=ON \ - -D ARCH="i686" \ - -D BUILD_64=OFF \ - -D CMAKE_BUILD_TYPE=Release \ - -D BUILD_TAG="win-x32" \ - -D CMAKE_TOOLCHAIN_FILE=../../cmake/32-bit-toolchain.cmake \ - -D MSYS2_FOLDER="$FOLDER" \ - ../../ - - make -j"$HOST_NCORES" wallet cryptonote_protocol || exit 1 - fi -else - # OS is not windows - mkdir -p build/release && - cd build/release && - cmake -DCMAKE_BUILD_TYPE=Release ../../ - make -j"$HOST_NCORES" wallet cryptonote_protocol || exit 1 -fi -cd ../../../../ - -# build libmonero-cpp shared library -mkdir -p build && -cd build && -cmake .. "${CMAKE_CCACHE_ARGS[@]}" && -cmake --build . && -make . -cd ../../../ - -# build libmonero-python shared library -mkdir -p build && -cd build && -cmake .. -make -j"$HOST_NCORES" +case "$(uname -s)" in + # the script of monero-cpp has the toolchain of msys2, as in the steps of the README for Windows + MINGW64_NT*|MSYS*) + # monero-cpp has to be told to use ccache, monero-project and the module look for it themselves + ccache_args=() + if command -v ccache > /dev/null 2>&1; then + ccache_args=(-DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache) + fi + (cd "$root/external/monero-cpp" && ./bin/build_libmonero_cpp.sh ${ccache_args[@]+"${ccache_args[@]}"});; + # the one of CI, which expects the submodules of monero-project to be there + *) + git -C "$root/external/monero-cpp/external/monero-project" submodule update --init --force + "$root/bin/build_monero_cpp.sh";; +esac +cmake -S "$root" -B "$root/build" +cmake --build "$root/build" -j"${JOBS:-3}" diff --git a/bin/check_links.sh b/bin/check_links.sh index 9d15ace5..9dce3aca 100755 --- a/bin/check_links.sh +++ b/bin/check_links.sh @@ -3,6 +3,8 @@ # workflow runs this script. lychee is downloaded once into .cache, from its release on GitHub, and checked against the sha256 of the # release. The configuration of lychee is lychee.toml. # +# ./bin/check_links.sh [options of lychee] as -vv, which shows where each redirect goes +# # GITHUB_TOKEN a token for the links to GitHub, which answers fewer requests without one: export GITHUB_TOKEN=$(gh auth token) set -euo pipefail @@ -53,13 +55,13 @@ fi cd "$root" # lychee.toml of the root is read on its own if [ -z "${GITHUB_STEP_SUMMARY:-}" ]; then - exec "$lychee" --no-progress "${inputs[@]}" + exec "$lychee" --no-progress "$@" "${inputs[@]}" fi # in CI, the report goes to the summary of the run as well report=$(mktemp) status=0 -"$lychee" --no-progress "${inputs[@]}" 2>&1 | tee "$report" || status=$? +"$lychee" --no-progress "$@" "${inputs[@]}" 2>&1 | tee "$report" || status=$? { echo '### Links'; echo; echo '```'; cat "$report"; echo '```'; } >> "$GITHUB_STEP_SUMMARY" rm -f "$report" exit "$status" diff --git a/bin/docs.sh b/bin/docs.sh index 4207436e..cbe28bb1 100755 --- a/bin/docs.sh +++ b/bin/docs.sh @@ -3,16 +3,20 @@ # They are installed in .cache, again when the requirements change. # # ./bin/docs.sh serve the site at http://127.0.0.1:8000, rebuilt at every change -# ./bin/docs.sh build the site in docs/mkdocs/public, strict as in CI: a docstring or a reference that does not resolve fails +# ./bin/docs.sh check the code of the examples only +# ./bin/docs.sh build the code of the examples checked and then the site in docs/mkdocs/public, strict, as in CI: an example that +# does not pass bin/check_examples.py or a docstring or a reference that does not resolve fails set -euo pipefail root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) requirements="$root/docs/mkdocs/requirements.in" -case "${1:-serve}" in +command=${1:-serve} +case "$command" in serve) args=(serve);; build) args=(build --strict);; - *) echo "usage: $0 [serve|build]" >&2; exit 1;; + check) args=();; + *) echo "usage: $0 [serve|build|check]" >&2; exit 1;; esac # in a folder of its own, not in a virtual environment: Debian and Ubuntu need python3-venv for one @@ -23,5 +27,14 @@ if [ ! -f "$packages/.installed" ]; then touch "$packages/.installed" fi +# the code of the examples first, as in CI +if [ "$command" != serve ]; then + PYTHONPATH="$packages" python3 "$root/bin/check_examples.py" +fi +if [ "$command" = check ]; then + exit +fi + cd "$root/docs/mkdocs" -PYTHONPATH="$packages" python3 -m mkdocs "${args[@]}" +# exec: who stops this script, as the stop button of VS Code, stops the server +PYTHONPATH="$packages" exec python3 -m mkdocs "${args[@]}" diff --git a/bin/lint_workflows.sh b/bin/lint_workflows.sh index 1f781b72..681732e5 100755 --- a/bin/lint_workflows.sh +++ b/bin/lint_workflows.sh @@ -54,5 +54,6 @@ status=0 echo "actionlint $actionlint_version" "$actionlint" -color || status=1 echo "zizmor $zizmor_version" -"$zizmor/bin/zizmor" .github || status=1 +# no bars of progress: in a terminal they break into the lines of the findings, which the problem matcher of VS Code reads +"$zizmor/bin/zizmor" --no-progress .github || status=1 exit $status diff --git a/conftest.py b/conftest.py index 089b2043..8e5cae70 100644 --- a/conftest.py +++ b/conftest.py @@ -29,11 +29,57 @@ def _crash_message(report: pytest.TestReport) -> str: return str(message) if message else (report.longreprtext or "unknown") +def _outcome(report: pytest.TestReport) -> Optional[str]: + """The word of the terminal for the result of a phase of a test, None for a setup or a teardown that passed.""" + if hasattr(report, "wasxfail"): + return "XPASS" if report.passed else "XFAIL" + if report.failed: + return "FAILED" if report.when == "call" else "ERROR" + if report.skipped: + return "SKIPPED" + return "PASSED" if report.when == "call" else None + + +def _details(report: pytest.TestReport) -> str: + """What the terminal says about a result: why a test is an expected failure or was skipped, the traceback of a failure.""" + reason: Optional[str] = getattr(report, "wasxfail", None) + if reason is not None: + return f": {reason}" + # a skip: the file, the line and the reason + if report.skipped and isinstance(report.longrepr, tuple): + return f": {report.longrepr[2]}" + return f"\n{report.longreprtext}" if report.failed else "" + + +# the log file has what the terminal shows of the tests too: which one runs, its result and the summary. At the DEBUG level, which goes +# to the file and not to the console, where pytest writes them already + +def pytest_runtest_logstart(nodeid: str) -> None: + logger.debug(f"TEST {nodeid}") + + def pytest_runtest_logreport(report: pytest.TestReport) -> None: - if report.outcome != "rerun": # type: ignore # set by pytest-rerunfailures + if report.outcome == "rerun": # type: ignore # set by pytest-rerunfailures + logger.error(f"EXPECTED FAILURE: {_crash_message(report)}") + logger.warning(f"RERUN {report.nodeid}") + return + outcome: Optional[str] = _outcome(report) + if outcome is not None: + logger.debug(f"{outcome} {report.nodeid}{_details(report)}") + + +def pytest_sessionfinish(session: pytest.Session) -> None: + plugin: object = session.config.pluginmanager.getplugin("terminalreporter") + reporter: Optional[pytest.TerminalReporter] = cast(Optional[pytest.TerminalReporter], plugin) + if reporter is None: return - logger.error(f"EXPECTED FAILURE: {_crash_message(report)}") - logger.warning(f"RERUN {report.nodeid}") + reports: dict[str, list[pytest.TestReport]] = cast(dict[str, list[pytest.TestReport]], reporter.stats) + for outcome, key in (("FAILED", "failed"), ("ERROR", "error")): + for report in reports.get(key, []): + logger.debug(f"SUMMARY {outcome} {report.nodeid}") + # the counts of the last line of the terminal, as "2 failed, 886 passed" + counts, _ = reporter.build_summary_stats_line() + logger.debug(f"SUMMARY {', '.join(text for text, _ in counts)}") def pytest_configure(config: pytest.Config) -> None: diff --git a/debian/set-version.sh b/debian/set-version.sh index b00c495a..9c087074 100755 --- a/debian/set-version.sh +++ b/debian/set-version.sh @@ -1,7 +1,7 @@ #!/bin/sh # Adds an entry to debian/changelog for the version declared in pyproject.toml, so the -# version is not repeated here. The package is named like python3-monero_0.9.11-1noble1_amd64.deb. -# With a snapshot, such as the commit that is built, it is python3-monero_0.9.11~git1a2b3c4-1noble1_amd64.deb: the tilde sorts it +# version is not repeated here. The package is named like python3-monero_0.9.13-1noble1_amd64.deb. +# With a snapshot, such as the commit that is built, it is python3-monero_0.9.13~git1a2b3c4-1noble1_amd64.deb: the tilde sorts it # before the release, so a release is always newer than the snapshots that came before it. # # usage: debian/set-version.sh [distribution [snapshot]] the distribution is the one of the system by default diff --git a/docs/mkdocs/docs/en/api/architecture.md b/docs/mkdocs/docs/en/api/architecture.md index b5fa93f2..4c4b6bf6 100644 --- a/docs/mkdocs/docs/en/api/architecture.md +++ b/docs/mkdocs/docs/en/api/architecture.md @@ -16,7 +16,7 @@ binding to the C++ of monero-cpp, and from there to the wallet of monero, `walle | Layer | Where | What it is | | --- | --- | --- | | Python | your application | `from monero import ...`: the classes of the diagram, with the types of the stubs | -| The module `monero` | `src/cpp` | one compiled module (`monero.cpython-*.so`, `.pyd` on Windows), made with [pybind11](https://pybind11.readthedocs.io){ target="_blank" rel="noopener" }: it binds the classes of monero-cpp, and has no Python code of its own | +| The module `monero` | `src/cpp` | one compiled module (`monero.cpython-*.so`, `.pyd` on Windows), made with [pybind11](https://pybind11.readthedocs.io/en/stable/){ target="_blank" rel="noopener" }: it binds the classes of monero-cpp, and has no Python code of its own | | The stubs | `src/monero/*.pyi` | the types and the docstrings of every class and function, installed next to the module with `py.typed`: type checkers and editors read them, and the [API Reference](wallet.md) is made from them | | monero-cpp | `external/monero-cpp` | the data model and the interfaces of the daemon and of the wallet, with their implementations, in C++ | | monero-project | `external/monero-cpp/external/monero-project` | `wallet2`, the wallet of monero, and the code that `monerod` and `monero-wallet-rpc` are made of | diff --git a/docs/mkdocs/docs/en/api/equality.md b/docs/mkdocs/docs/en/api/equality.md index 7c9560cf..a5e19af3 100644 --- a/docs/mkdocs/docs/en/api/equality.md +++ b/docs/mkdocs/docs/en/api/equality.md @@ -12,8 +12,13 @@ pick the right one, since Java writes them the other way around. Two objects are equal if they have the same class and the same JSON, the one of [`serialize`][monero.SerializableStruct.serialize]: ```python -tx1: MoneroTxWallet = wallet.get_tx(tx_hash) -tx2: MoneroTxWallet = wallet.get_tx(tx_hash) +from monero import MoneroBlock, MoneroOutputWallet, MoneroTxConfig, MoneroTxWallet, MoneroWalletRpc + +wallet = MoneroWalletRpc("http://localhost:38083", "rpc_user", "abc123") +tx_hash: str = "..." + +tx1: MoneroTxWallet | None = wallet.get_tx(tx_hash) +tx2: MoneroTxWallet | None = wallet.get_tx(tx_hash) assert tx1 == tx2 # the same values assert tx1 is not tx2 # two objects ``` @@ -37,7 +42,8 @@ The objects can be changed, so they are not hashable: they can not be keys of a `TypeError`. Key them by what identifies them: ```python -txs_by_hash: dict[str, MoneroTxWallet] = {tx.hash: tx for tx in txs} +txs: list[MoneroTxWallet] = wallet.get_txs() +txs_by_hash: dict[str, MoneroTxWallet] = {tx.hash: tx for tx in txs if tx.hash is not None} ``` or, to tell the objects apart rather than their values, by their `id()` while a reference keeps them alive (see below). @@ -48,6 +54,7 @@ An object of the model is a Python object around a C++ object. The bindings give as one is alive, so the back references are the objects that they point to: ```python +tx: MoneroTxWallet = txs[0] for output in tx.outputs: assert output.tx is tx assert tx.block is None or any(block_tx is tx for block_tx in tx.block.txs) @@ -57,6 +64,9 @@ When no Python object is alive, the next access makes a new one: the `id()` of a next. Keep a reference before taking it: ```python +blocks: list[MoneroBlock] = [] +seen_blocks: set[int] = set() + block: MoneroBlock | None = tx.block if block is not None and id(block) not in seen_blocks: seen_blocks.add(id(block)) @@ -73,10 +83,12 @@ the same order. An object is compared by its JSON, so `in` looks for the same ob does not serialize the txs of the block. Their items are still the objects that they hold: ```python -copy: MoneroOutputWallet = output.copy() -assert copy == output -assert copy in output.tx.outputs # an equal one -assert any(tx_output is output for tx_output in output.tx.outputs) # the same object +wallet_output: MoneroOutputWallet = wallet.get_outputs()[0] +copy: MoneroOutputWallet = wallet_output.copy() +assert copy == wallet_output +assert wallet_output.tx is not None +assert copy in wallet_output.tx.outputs # an equal one +assert any(tx_output is wallet_output for tx_output in wallet_output.tx.outputs) # the same object ``` ## Representation @@ -111,6 +123,7 @@ assertEquals(configCopy, config); // with the same values In Python, the first is `is not`, not `!=`: `configCopy != config` would fail, since the copy has the same values. ```python +config = MoneroTxConfig() config_copy: MoneroTxConfig = config.copy() # ... assert config_copy is not config diff --git a/docs/mkdocs/docs/en/contributing/changes.md b/docs/mkdocs/docs/en/contributing/changes.md index da3b1d01..3b328c5a 100644 --- a/docs/mkdocs/docs/en/contributing/changes.md +++ b/docs/mkdocs/docs/en/contributing/changes.md @@ -40,8 +40,7 @@ A change of the library has its parts in more than one place: the C++ of the bin | `pytest -m integration` | the integration tests, on the network of `tests/docker-compose.yml` | a change of what talks to a daemon or a wallet ([Running the Tests](../tests/running/index.md)) | | the **Problems** of VS Code | the types of the tests and of the scripts, with Pylance in strict mode | a change of Python | | `python3 bin/lint_bindings.py` | the bindings, against what stubgen makes of them | a change of `src/cpp` | -| `python3 bin/check_examples.py` | the code of the docs and of `README.md`, against the stubs | a change of a stub or of an example | -| `./bin/docs.sh build` | the site, strict as in CI: a reference or a link that does not resolve fails it | a change of the docs or of a stub | +| `./bin/docs.sh build` | the code of the docs and of `README.md` against the stubs, and the site, strict as in CI: a reference or a link that does not resolve fails it | a change of the docs, of a stub or of `README.md` | | `./bin/lint_workflows.sh` | the workflows, with the actionlint and zizmor of CI | a change of `.github` | | `./bin/check_links.sh` | the links to the web of the docs, the stubs and `README.md`, with the lychee of CI | a change of a link | | `./bin/check_spelling.sh` | the spelling of the docs, the docstrings, the comments and the messages, with the codespell of CI; `-w` fixes the typos with one correction | always | diff --git a/docs/mkdocs/docs/en/contributing/commits.md b/docs/mkdocs/docs/en/contributing/commits.md index 46e18706..ae475580 100644 --- a/docs/mkdocs/docs/en/contributing/commits.md +++ b/docs/mkdocs/docs/en/contributing/commits.md @@ -26,7 +26,7 @@ The scope is the part of the repository that the change is about: | `release` | the release workflow, `release.yml` | | `bin` | the scripts of `bin/` | | `vscode` | the configuration of `.vscode` | -| `version` | the version of `pyproject.toml`, for a release: `version: bump to v0.9.11` | +| `version` | the version of `pyproject.toml`, for a release: `version: bump to v0.9.13` | A commit has one change: a fix and a refactoring are two commits. A message says what the change does, and why when it is not evident from what it does. diff --git a/docs/mkdocs/docs/en/contributing/docs.md b/docs/mkdocs/docs/en/contributing/docs.md index 6fe8c9c9..78ea6b34 100644 --- a/docs/mkdocs/docs/en/contributing/docs.md +++ b/docs/mkdocs/docs/en/contributing/docs.md @@ -15,7 +15,8 @@ The site is made with [MkDocs](https://www.mkdocs.org){ target="_blank" rel="noo | How | What | | --- | --- | | `./bin/docs.sh serve` | the site at `http://127.0.0.1:8000`, built again at every change | -| `./bin/docs.sh build` | the site in `docs/mkdocs/public`, strict as in CI | +| `./bin/docs.sh build` | the code of the examples checked, and the site in `docs/mkdocs/public`, strict as in CI | +| `./bin/docs.sh check` | the code of the examples checked only | | **Run and Debug → `docs: build and serve`** in VS Code | the strict build and the server, opened in the browser; a breakpoint in the extensions of griffe stops | `bin/docs.sh` installs the tools of `requirements.in` in `.cache` the first time, and again when the file changes. @@ -81,10 +82,10 @@ A page of the API is the directive of the class, `::: monero.MoneroWallet`, afte ## The code of the examples The ` ```python ` blocks of the pages and of `README.md` are checked against the stubs with pyright, by `bin/check_examples.py`, in CI -and before a pull request: +and before a pull request, as the first step of the build: ```bash -python3 bin/check_examples.py +./bin/docs.sh build ``` - The blocks of a page are one file: a block can use what a block before it defined. @@ -111,7 +112,7 @@ The path is from the root of the repository. A snippet that is not found fails t ## The macros -A page can use the variables of [mkdocs-macros](https://mkdocs-macros-plugin.readthedocs.io){ target="_blank" rel="noopener" }, in +A page can use the variables of [mkdocs-macros](https://mkdocs-macros-plugin.readthedocs.io/en/latest/){ target="_blank" rel="noopener" }, in `{{ ... }}` and `{% ... %}`: | Variable | Where it comes from | Used by | @@ -126,8 +127,7 @@ front matter. | Command | What it checks | | --- | --- | -| `./bin/docs.sh build` | the site, strict | -| `python3 bin/check_examples.py` | the code of the examples | +| `./bin/docs.sh build` | the code of the examples and the site, strict | | `./bin/check_spelling.sh` | the spelling, with the words that are not typos in `.codespellrc` | | `./bin/check_links.sh` | the links to the web, which CI checks every week | diff --git a/docs/mkdocs/docs/en/getting_started/installation.md b/docs/mkdocs/docs/en/getting_started/installation.md index 922b606a..f272a9d1 100644 --- a/docs/mkdocs/docs/en/getting_started/installation.md +++ b/docs/mkdocs/docs/en/getting_started/installation.md @@ -27,7 +27,7 @@ the Python of its name, in a virtual environment of that Python: ```bash python3.14 -m venv .venv . .venv/bin/activate -pip install monero-0.9.11-cp314-cp314-macosx_15_0_arm64.whl +pip install monero-0.9.13-cp314-cp314-macosx_15_0_arm64.whl ``` The `` of a wheel is the oldest version of macOS that it runs on. The libraries that the module needs are in the wheel, and the diff --git a/docs/mkdocs/docs/en/tests/index.md b/docs/mkdocs/docs/en/tests/index.md index 868086bb..486279e5 100644 --- a/docs/mkdocs/docs/en/tests/index.md +++ b/docs/mkdocs/docs/en/tests/index.md @@ -3,7 +3,7 @@ title: Tests --- # Tests -The tests are written with [pytest](https://docs.pytest.org/) and are in [tests/](https://github.com/libmonero/monero-python/tree/main/tests). +The tests are written with [pytest](https://docs.pytest.org/en/stable/) and are in [tests/](https://github.com/libmonero/monero-python/tree/main/tests). They test the module as a user of the library does: they import `monero`, the module that CMake builds, and call it. There are about 1200 of them, on the models, the utilities, the daemon and the three wallet types. diff --git a/docs/mkdocs/docs/en/tests/running/results.md b/docs/mkdocs/docs/en/tests/running/results.md index 9664ae76..57105696 100644 --- a/docs/mkdocs/docs/en/tests/running/results.md +++ b/docs/mkdocs/docs/en/tests/running/results.md @@ -30,7 +30,7 @@ pytest -m unit -q -rfE --tb=short | Where | What | | --- | --- | | the console | the `INFO` messages of the tests, as they run (`log_cli` in `pytest.ini`) | -| `test_logs/monero_tests_python_.log` | the `DEBUG` messages of the tests, one file for each run | +| `test_logs/monero_tests_python_.log` | the `DEBUG` messages of the tests and, as in the terminal, which test runs, its result with the traceback of a failure, and the summary; one file for each run | | `test_logs/monero_tests_cpp_.log` | the log of monero-cpp, at the `log_level` of `config.ini` | ```bash diff --git a/docs/mkdocs/docs/en/tests/vscode/index.md b/docs/mkdocs/docs/en/tests/vscode/index.md index 9d7b540a..5fd42847 100644 --- a/docs/mkdocs/docs/en/tests/vscode/index.md +++ b/docs/mkdocs/docs/en/tests/vscode/index.md @@ -25,11 +25,34 @@ VS Code proposes the extensions of `.vscode/extensions.json` when the folder is | GitHub Actions | the workflows of CI | | ShellCheck | the scripts of `bin/` | | Coverage Gutters | the coverage of the tests, in the editor | -| Tasks | the most used tasks as buttons of the status bar, and the others from its `...` button | + +The buttons of the status bar are of an extension of the repository, `.vscode/extensions/status-bar-buttons`: + +| Button | What it shows | +| --- | --- | +| Build | runs `build: monero-python` | +| Docker | **Setup Docker** when the network of the integration tests is down and **Stop Docker** when it is up, also when `docker compose` is run from a terminal; a warning icon, with their names in the tooltip, when some of its services do not run | +| Docs | **Build Docs**, which runs `docs: serve`; a spinning icon while the site is built and **Stop Docs** once it is served | +| Lint | a menu that runs `lint: links`, `lint: spelling`, `lint: workflows` or `lint: examples` | + +While a task of `.vscode/tasks.json` runs, the buttons of the other tasks are gray and do nothing, so that two of them do not work +at once; their tooltip says what they wait for. The server of the docs makes them wait only while it builds the site. A task run +from **Terminal → Run Task**, or from a launch configuration, does not wait. + +It also shows as popups what a lint task finds: one for each of the first three problems, with a button that opens it, and one +for the others, which opens **Problems**. The redirects of the links are a popup of warning, and the terminal shows where each one goes +(`./bin/check_links.sh -vv`). A hint of lychee is a popup of warning too: the task keeps a copy of its output in +`.cache/lint-links.log` for them. + +At the end of a build task it shows a popup with the result and the time, if the build failed or took more than 30 seconds, and +after `build: monero-python` it reads the tests of the **Testing** panel again. + +VS Code does not install it on its own: run **Extensions: Show Recommended Extensions** and install it from +**Workspace Recommendations**. It needs a trusted folder. ## First setup -From **Terminal → Run Task**, or the `...` button of the status bar: +From **Terminal → Run Task**: 1. `setup: system dependencies`: the packages of apt that the build needs (`bin/install_dependencies_linux.sh`). 2. `setup: venv`: the virtual environment `.venv`, with the tools of the build, of the tests and of the docs @@ -52,9 +75,18 @@ From **Terminal → Run Task**, or the `...` button of the status bar: | `tests: unit (coverage)` | `pytest -m unit` with the coverage of the tests in `coverage.xml`, as in CI | | `lint: workflows` | actionlint and zizmor on the workflows, with the versions of CI | | `lint: links` | lychee on the links to the web of the docs, the stubs and the README, with the version of CI | +| `lint: examples` | the code of the docs and of the README against the stubs: the errors show in **Problems** | | `lint: spelling` | codespell on the files of git, with the version of CI: the typos show in **Problems** | | `docs: serve` | the docs at `http://127.0.0.1:8000`, built again at every change | | `docs: build` | the docs, strict as in CI | -What the build, the tests and the lint find goes to **Problems**, and to the counter of errors and warnings of the status bar: an error -of the compiler, a test that fails, a typo, a broken link, each one with a link to its file. +The build tasks run 3 compilers at once, at a low priority. The environment variable `MONERO_JOBS` changes their number, as 1 on a +machine with little memory, for instance in your user settings: + +```json +"terminal.integrated.env.linux": { "MONERO_JOBS": "1" } +``` + +What the build, the tests, the docs and the lint find goes to **Problems**, and to the counter of errors and warnings of the status +bar: an error of the compiler, a test that fails, a wrong example or reference of the docs, a typo, a broken link, each one with a +link to its file. diff --git a/pyproject.toml b/pyproject.toml index b540fdf5..881d5a19 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -2,7 +2,7 @@ name = "monero" # the only place where the version is declared: CMakeLists.txt, debian/set-version.sh and # the release workflow read it from here -version = "0.9.11" +version = "0.9.13" description = "A Python library for using Monero" authors = [ { name = "Libmonero", email = "libmonero@protonmail.com" } diff --git a/tests/utils/wallet_transfers_utils.py b/tests/utils/wallet_transfers_utils.py index 29959b6a..13b87933 100644 --- a/tests/utils/wallet_transfers_utils.py +++ b/tests/utils/wallet_transfers_utils.py @@ -31,7 +31,7 @@ def get_and_test_transfers( :returns list[MoneroTransfer]: the fetched, tested transfers. """ copy: Optional[MoneroTransferQuery] = query.copy() if query is not None else None - + transfers: list[MoneroTransfer] if query is not None: transfers = wallet.get_transfers(query)