File: SyncScreenshots.php

package info (click to toggle)
matomo 5.5.1%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 73,596 kB
  • sloc: php: 231,041; javascript: 102,286; python: 202; xml: 189; sh: 172; makefile: 20; sql: 10
file content (251 lines) | stat: -rw-r--r-- 8,269 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
<?php

/**
 * Matomo - free/libre analytics platform
 *
 * @link    https://matomo.org
 * @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 */

namespace Piwik\Plugins\TestRunner\Commands;

use Piwik\Container\StaticContainer;
use Piwik\Development;
use Piwik\Filesystem;
use Piwik\Http;
use Piwik\Plugin\ConsoleCommand;
use Piwik\Log\LoggerInterface;

/**
 * Downloads the UI tests screenshots from artifacts server into the local repository.
 *
 * This command helps to synchronize the screenshots after they have changed.
 */
class SyncScreenshots extends ConsoleCommand
{
    /**
     * @var LoggerInterface
     */
    private $logger;

    public const BUILDURL = "https://builds-artifacts.matomo.org";

    public function __construct()
    {
        $this->logger = StaticContainer::get(LoggerInterface::class);

        parent::__construct();
    }

    public function isEnabled(): bool
    {
        return Development::isEnabled();
    }

    protected function configure()
    {
        $this->setName('tests:sync-ui-screenshots');
        $this->setAliases(['development:sync-ui-test-screenshots']);
        $this->setDescription(
            'For Piwik core devs. Copies screenshots from github artifacts to the tests/UI/expected-screenshots/ folder'
        );
        $this->addRequiredArgument(
            'buildnumber',
            'Travis build number you want to sync.'
        );
        $this->addOptionalArgument(
            'screenshotsRegex',
            'A regex to use when selecting screenshots to copy. If not supplied all screenshots are copied.',
            ['.*'],
            true
        );
        $this->addOptionalValueOption(
            'repository',
            'r',
            'Repository name you want to sync screenshots for.',
            'matomo-org/matomo'
        );
        $this->addOptionalValueOption(
            'http-user',
            '',
            'the HTTP AUTH username (for premium plugins where artifacts are protected)'
        );
        $this->addOptionalValueOption(
            'http-password',
            '',
            'the HTTP AUTH password (for premium plugins where artifacts are protected)'
        );
    }

    protected function doExecute(): int
    {
        $input = $this->getInput();
        $output = $this->getOutput();
        $buildNumber      = $input->getArgument('buildnumber');
        $screenshotsRegex = $input->getArgument('screenshotsRegex');
        $repository       = $input->getOption('repository');
        $httpUser         = $input->getOption('http-user');
        $httpPassword     = $input->getOption('http-password');

        $screenshots = $this->getScreenshotList($repository, $buildNumber, $httpUser, $httpPassword);

        $this->logger->notice('Downloading {number} screenshots', ['number' => count($screenshots)]);
        foreach ($screenshots as $name => $url) {
            if (empty($name)) {
                continue;
            }

            if (is_array($screenshotsRegex)) {
                foreach ($screenshotsRegex as $regex) {
                    if (preg_match('/' . $regex . '/', $name)) {
                        $this->logger->info('Downloading {name}', ['name' => $name]);
                        $this->downloadScreenshot($url, $repository, $name, $httpUser, $httpPassword);
                        break;
                    }
                }
            } elseif (preg_match('/' . $screenshotsRegex . '/', $name)) {
                $this->logger->info('Downloading {name}', ['name' => $name]);
                $this->downloadScreenshot($url, $repository, $name, $httpUser, $httpPassword);
            }
        }

        $this->displayGitInstructions($repository);

        return self::SUCCESS;
    }

    private function getScreenshotList($repository, $buildNumber, $httpUser = null, $httpPassword = null)
    {
        $url = sprintf('%s/api/%s/%s', self::BUILDURL, $repository, $buildNumber);

        $this->logger->debug('Fetching {url}', ['url' => $url]);

        $response   = Http::sendHttpRequest(
            $url,
            $timeout = 160,
            $userAgent = null,
            $destinationPath = null,
            $followDepth = 0,
            $acceptLanguage = false,
            $byteRange = false,
            $getExtendedInfo = true,
            $httpMethod = 'GET',
            $httpUser,
            $httpPassword
        );
        $httpStatus = $response['status'];
        if ($httpStatus == '200') {
            return json_decode($response['data'], true);
        }
        if ($httpStatus == '401') {
            throw new \Exception('HTTP 401 - Auth username and password are invalid');
        }
        $this->logger->debug('Response content: {content}', ['content' => $response['data']]);
        throw new \Exception("Failed downloading diffviewer from $url - Got HTTP status $httpStatus");
    }

    private function downloadScreenshot($url, $repository, $screenshot, $httpUser, $httpPassword)
    {
        $downloadTo = $this->getDownloadToPath($repository, $screenshot) . $screenshot;

        $url = self::BUILDURL . $url;

        $this->logger->debug("Downloading {url} to {destination}", ['url' => $url, 'destination' => $downloadTo]);

        Http::sendHttpRequest(
            $url,
            $timeout = 160,
            $userAgent = null,
            $downloadTo,
            $followDepth = 0,
            $acceptLanguage = false,
            $byteRange = false,
            $getExtendedInfo = true,
            $httpMethod = 'GET',
            $httpUser,
            $httpPassword
        );
    }

    private function displayGitInstructions($repository)
    {
        $this->getOutput()->writeln(
            '<comment>If all downloaded screenshots are valid you may push them with these commands:</comment>'
        );
        $downloadToPath = $this->getDownloadToPath($repository);
        $commands       = "

# Starts here
cd $downloadToPath
git pull
git add .
git status
git commit -m 'UI tests: ...' # Write a good commit message, eg. 'Fixed UI test failure caused by change introduced in X which caused failure by Y'
echo -e \"\n--> Check the commit above is correct... <---\n\"
sleep 7
git push";

        if ($repository === 'matomo-org/matomo') {
            $commands .= "
cd ../../../";
        } else {
            $commands .= "
cd ../../../../../";
        }

        $this->getOutput()->writeln($commands);
    }

    private function getDownloadToPath($repository, $fileName = false)
    {
        $plugin = $this->getPluginName($repository, $fileName);

        if (empty($plugin)) {
            return PIWIK_DOCUMENT_ROOT . "/tests/UI/expected-screenshots/";
        }

        $possibleSubDirs = [
            'expected-screenshots',
            'expected-ui-screenshots',
        ];

        foreach ($possibleSubDirs as $subDir) {
            $downloadTo = PIWIK_DOCUMENT_ROOT . "/plugins/$plugin/tests/UI/$subDir/";
            if (is_dir($downloadTo)) {
                return $downloadTo;
            }

            // Maybe the plugin is using folder "Test/" instead of "tests/"
            $downloadTo = str_replace("tests/", "Test/", $downloadTo);
            if (is_dir($downloadTo)) {
                return $downloadTo;
            }
        }
        throw new \Exception("Download to path could not be found: $downloadTo");
    }

    private function getPluginName($repository, $fileName)
    {
        [$org, $repository] = explode('/', $repository, 2);

        if (strpos($repository, 'plugin-') === 0) {
            return substr($repository, strlen('plugin-'));
        }

        // determine plugin based on the test name
        if (!empty($fileName)) {
            [$testName, $_null] = explode('_', $fileName, 2);
            $foundExistingFiles = Filesystem::globr(PIWIK_DOCUMENT_ROOT, $fileName);
            $foundTestSpecs     = Filesystem::globr(PIWIK_DOCUMENT_ROOT, $testName . '_spec.js');
            $filesToCheck       = $foundExistingFiles + $foundTestSpecs;

            foreach ($filesToCheck as $file) {
                if (preg_match('/plugins\/([^\/]+)\//i', $file, $plugin)) {
                    return $plugin[1];
                }
            }
        }

        return null;
    }
}