Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Исправление ошибки публикации по вложенным папкам в /build/out/allure #141

Open
wants to merge 5 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 25 additions & 25 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -1,25 +1,25 @@
The MIT License (MIT)
=====================
Copyright © `2020` `First Bit Semenovskaya, Первый Бит Семеновская`
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the “Software”), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The MIT License (MIT)
=====================

Copyright © `2020` `First Bit Semenovskaya, Первый Бит Семеновская`

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the “Software”), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
47 changes: 43 additions & 4 deletions src/ru/pulsar/jenkins/library/steps/PublishAllure.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,10 @@ class PublishAllure implements Serializable {
}

def run() {

Logger.printLocation()

if (config == null) {
Logger.println("jobConfiguration is not initialized")
Logger.println('jobConfiguration is not initialized')
return
}

Expand All @@ -44,16 +43,37 @@ class PublishAllure implements Serializable {

FilePath allurePath = FileUtils.getFilePath("$env.WORKSPACE/build/out/allure")
if (!allurePath.exists()) {
Logger.println("Отсутствуют результаты allure для публикации")
Logger.println('Отсутствуют результаты allure для публикации')
return
}

List<String> results = new ArrayList<>()

int directoryCount = allurePath.listDirectories().size()
Logger.println("Log: Количество подкаталогов в $allurePath: $directoryCount")

FilePath workSpacePath = FileUtils.getFilePath("$env.WORKSPACE")
String basePath = replaceBackslashesWithSlashes(workSpacePath.toString())
Logger.println("Log: workSpacePath = $workSpacePath, basePath = $basePath")

allurePath.listDirectories().each { FilePath filePath ->
results.add(FileUtils.getLocalPath(filePath))
FilePath pathCurrent = FileUtils.getFilePath("$filePath")
String pathdir = FileUtils.getLocalPath(pathCurrent)
Logger.println("Log: pathCurrent = $pathCurrent, pathdir = $pathdir")

String rezultPath = getRelativePath(pathdir, basePath)
Logger.println("Log: pathdir = $pathdir, basePath = $basePath. Результат через getRelativePath() = $rezultPath")
results.add(rezultPath)

//String pathdir = FileUtils.getLocalPath(filePath)
//results.add(FileUtils.getLocalPath(filePath))
//Logger.println("Log: Результат для добавления в allure getLocalPath($pathCurrent): $pathdir")
}

String pathAllure = FileUtils.getLocalPath(allurePath)
Logger.println("Log: если в подкаталогах allure пусто, то будет добавлен только путь на основе getLocalPath($allurePath): $pathAllure")
if (results.isEmpty()) {
Logger.println('Log: результат пустой и фиксиурем путь выше')
results.add(FileUtils.getLocalPath(allurePath))
}

Expand All @@ -67,4 +87,23 @@ class PublishAllure implements Serializable {
Logger.println("Can't unstash $stashName")
}
}

private static replaceBackslashesWithSlashes(String path) {
return path.replace('\\', '/')
}

private static String getRelativePath(String absolutePath, String basePath) {
def normalizedAbsolutePath = new File(absolutePath).canonicalPath
def normalizedBasePath = new File(basePath).canonicalPath
Copy link
Member

@nixel2007 nixel2007 Jan 3, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Класс File использовать нужно использовать очень аккуратно, так как он разрешается на мастере, а не на агенте. Лучше работать через FilePath. Ну и соответственно вынести эту логику в FileUtils

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Класс File использовать нужно использовать очень аккуратно, так как он разрешается на мастере, а не на агенте. Лучше работать через FilePath. Ну и соответственно вынести эту логику в FileUtils

Груви не знаю. Через нейросеть эту функцию получил и применил, чтобы закрыть проблему.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тут не чистый груви, а с ограничениями дженкинса и его распределенной модели выполнения.


def relativePath = normalizedAbsolutePath.replaceFirst(normalizedBasePath, '')

// Убираем начальный '/' если он есть
if (relativePath.startsWith('/')) {
relativePath = relativePath.substring(1)
}

return relativePath
}
Comment on lines +95 to +107
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Метод getRelativePath и риски совпадения путей
Расчёт относительного пути путём замены normalizedBasePath на пустую строку подходит для большинства случаев. Однако если часть normalizedBasePath может встречаться в середине normalizedAbsolutePath, это вызовет ложное срабатывание. Рекомендуется проверить, что путь действительно начинается с normalizedBasePath.


}
1 change: 1 addition & 0 deletions src/ru/pulsar/jenkins/library/steps/SonarScanner.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ class SonarScanner implements Serializable {
}
} else (branchAnalysisConfiguration == BranchAnalysisConfiguration.AUTO) {
// no-op
sonarCommand += ""
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Исправьте синтаксическую ошибку в условии else

В текущей реализации присутствует синтаксическая ошибка в условии else. Использование else (condition) некорректно в Groovy. Вместо этого следует использовать else if.

Примените следующие изменения:

-        } else (branchAnalysisConfiguration == BranchAnalysisConfiguration.AUTO) {
-            // no-op
-            sonarCommand += ""
+        } else if (branchAnalysisConfiguration == BranchAnalysisConfiguration.AUTO) {
+            // no-op
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
} else (branchAnalysisConfiguration == BranchAnalysisConfiguration.AUTO) {
// no-op
sonarCommand += ""
}
} else if (branchAnalysisConfiguration == BranchAnalysisConfiguration.AUTO) {
// no-op
}


String projectVersion = computeProjectVersion()
Expand Down
3 changes: 2 additions & 1 deletion src/ru/pulsar/jenkins/library/steps/Yaxunit.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,8 @@ class Yaxunit implements Serializable, Coverable {
FilePath pathToAllureReport = FileUtils.getFilePath("$env.WORKSPACE/$allureReport")
String allureReportDir = FileUtils.getLocalPath(pathToAllureReport.getParent())

pathToJUnitReport.copyTo(pathToAllureReport)
// * Закомментировано, т.к. ошибка формирования отчета allure
//pathToJUnitReport.copyTo(pathToAllureReport)

steps.stash(YAXUNIT_ALLURE_STASH, "$allureReportDir/**", true)
}
Expand Down
8 changes: 7 additions & 1 deletion src/ru/pulsar/jenkins/library/utils/FileUtils.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,17 @@ class FileUtils {
Path workspacePath = new File(env.WORKSPACE).toPath()
Path rawFilePath = new File(filePath.getRemote()).toPath()

return workspacePath.relativize(rawFilePath)
def str = workspacePath.relativize(rawFilePath)
.toString()
.replaceAll('\\\\\\\\', '/')
.replaceAll('\\\\', '/')
.toString()

if (str.startsWith("../")) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это сильно меняет логику работы этого метода

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

На сейчас эта функция работает не очень корректно. И явно это проблема раз на выходе может впереди быть "../". Функцию надо значительно модифицировать, т.к. она ключевая.

getLocalPath(c:\j\workspace\ins-lib_projects_ci_kyporos_main\build\out\allure\bdd) = "../c:/j/workspace/ins-lib_projects_ci_kyporos_main/build/out/allure/bdd"

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Меня смущает то, что никто из других пользователей с такой ошибкой не сталкивался. Может проблема в вашей версии дженкинса? Какая у вас?

str = str.substring(3)
}

return str
}

static void loadFile(String filePathFrom, def env, String filePathTo) {
Expand Down