Skip to content

Commit

Permalink
Имплементация загрузки из dt или 1cd
Browse files Browse the repository at this point in the history
  • Loading branch information
Segate-ekb committed Aug 24, 2024
1 parent a5613f4 commit 60e184c
Show file tree
Hide file tree
Showing 9 changed files with 156 additions and 37 deletions.
1 change: 1 addition & 0 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ plugins {

repositories {
mavenCentral()
maven(url = "https://repo.jenkins-ci.org/releases/")
}

tasks {
Expand Down
2 changes: 2 additions & 0 deletions resources/globalConfiguration.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@
"initMethod": "fromStorage",
"runMigration": true,
"additionalInitializationSteps": [],
"baseDBPath": "",
"vrunnerSettings": "",
"extensions": []
},
"bdd": {
Expand Down
8 changes: 8 additions & 0 deletions resources/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,14 @@
"type" : "string"
}
},
"vrunnerSettings" : {
"type" : "string",
"description" : "Путь к конфигурационному файлу vanessa-runner.\n По умолчанию не заполнено, требуется, если на этапе подготовки база загружается из архива.\n "
},
"baseDBPath" : {
"type" : "string",
"description" : "Путь к конфигурационному файлу эталонной базы данных.\n * По умолчанию не заполнен.\n * Указывается путь к файлу *.dt или *.1CD\n "
},
"extensions" : {
"type" : "array",
"description" : "Массив расширений для загрузки в конфигурацию.",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,18 @@ class InitInfoBaseOptions implements Serializable {
""")
String[] additionalInitializationSteps

@JsonPropertyDescription("""Путь к конфигурационному файлу vanessa-runner.
По умолчанию не заполнено, требуется, если на этапе подготовки база загружается из архива.
""")
String vrunnerSettings

@JsonPropertyDescription("""
Путь к конфигурационному файлу эталонной базы данных.
* По умолчанию не заполнен;
* Указывается путь к файлу *.dt или *.1CD.
""")
String baseDBPath

@JsonPropertyDescription("Массив расширений для загрузки в конфигурацию.")
Extension[] extensions

Expand Down Expand Up @@ -62,6 +74,8 @@ class InitInfoBaseOptions implements Serializable {
return "InitInfoBaseOptions{" +
"initMethod=" + initMethod +
", runMigration=" + runMigration +
", vrunnerSettings=" + vrunnerSettings +
", baseDBPath=" + baseDBPath +
", additionalInitializationSteps=" + additionalInitializationSteps +
", extensions=" + extensions +
'}'
Expand Down
68 changes: 68 additions & 0 deletions src/ru/pulsar/jenkins/library/steps/CreateInfobase.groovy
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package ru.pulsar.jenkins.library.steps

import ru.pulsar.jenkins.library.IStepExecutor
import ru.pulsar.jenkins.library.configuration.JobConfiguration
import ru.pulsar.jenkins.library.ioc.ContextRegistry
import ru.pulsar.jenkins.library.utils.Logger
import ru.pulsar.jenkins.library.utils.VRunner
import hudson.FilePath
import ru.pulsar.jenkins.library.utils.FileUtils

class CreateInfobase implements Serializable {

private final JobConfiguration config;

CreateInfobase(JobConfiguration config) {
this.config = config
}

def run() {
IStepExecutor steps = ContextRegistry.getContext().getStepExecutor()

Logger.printLocation()

def env = steps.env()

steps.installLocalDependencies();

String baseDBPath = config.initInfoBaseOptions.baseDBPath
if (baseDBPath == '') {
// Не указан путь к базе данных, создадим пустую базу данных.
createBase('', steps)
} else if (baseDBPath.endsWith('.1CD')) {
// Это файл базы данных 1С, просто скопируем его.
String pathToInfobase = "$env.WORKSPACE/build/ib/1Cv8.1CD"
FileUtils.loadFile(baseDBPath, env, pathToInfobase)
} else if (baseDBPath.endsWith('.dt')) {
// Это файл дампа БД, скопируем его и создадим БД.
String pathToDt = "$env.WORKSPACE/build/tmp/dump.dt"
FileUtils.loadFile(baseDBPath, env, pathToDt)
createBase('build/tmp/dump.dt', steps)
} else {
Logger.println("Неизвестный формат базы данных. Поддерживаются только .1CD и .dt")
}

}

private void createBase(String dtPath = '', def steps) {
Logger.println("Создание информационной базы")
String vrunnerPath = VRunner.getVRunnerPath();
def initCommand = "$vrunnerPath init-dev --ibconnection \"/F./build/ib\""
VRunner.exec(initCommand)

if (dtPath) {
// Загрузка из dt в vrunner 2.2.2 не работает корректно, потому инициировать через init-dev не получится.
def loadDtCommand = "$vrunnerPath restore --ibconnection \"/F./build/ib\" $dtPath"
VRunner.exec(loadDtCommand)

def updateDbCommand = "$vrunnerPath updatedb --ibconnection \"/F./build/ib\""
def options = config.initInfoBaseOptions

String vrunnerSettings = options.vrunnerSettings
if (vrunnerSettings && steps.fileExists(vrunnerSettings)) {
updateDbCommand += " --settings $vrunnerSettings"
}
VRunner.exec(updateDbCommand)
}
}
}
36 changes: 2 additions & 34 deletions src/ru/pulsar/jenkins/library/steps/GetExtensions.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,8 @@ class GetExtensions implements Serializable {
buildExtension(it, srcDir, vrunnerPath, steps)
} else if (it.initMethod == InitExtensionMethod.FILE){
Logger.println("Загрузка расширения ${it.name} из ${it.path}")
loadExtension(it, env)
String pathToExtension = "$pathToExtensionDir/${it.name}.cfe"
FileUtils.loadFile(it.path, env, pathToExtension)
} else {
Logger.println("Неизвестный метод инициализации расширения ${it.name}")
}
Expand All @@ -73,22 +74,6 @@ class GetExtensions implements Serializable {
}
}

private void loadExtension(Extension extension, def env) {
String pathToExtension = "$env.WORKSPACE/${EXTENSIONS_OUT_DIR}/${extension.name}.cfe"
FilePath localPathToExtension = FileUtils.getFilePath(pathToExtension)

if (isValidUrl(extension.path)) {
// If the path is a URL, download the file
localPathToExtension.copyFrom(new URL(extension.path))
} else {
// If the path is a local file, copy the file
String localPath = getAbsolutePath(extension.path, env)
FilePath localFilePath = FileUtils.getFilePath(localPath)
localPathToExtension.copyFrom(localFilePath)
}
}


private String initVRunnerPath() {
return VRunner.getVRunnerPath()
}
Expand All @@ -108,21 +93,4 @@ class GetExtensions implements Serializable {
steps.unzip(sourceDirName, EdtToDesignerFormatTransformation.EXTENSION_ZIP)
}
}

private static boolean isValidUrl(String url) {
try {
new URL(url)
return true
} catch (MalformedURLException e) {
return false
}
}

private static String getAbsolutePath(String path, def env) {
if (path.startsWith("/") || path.startsWith("\\") || path.matches("^[A-Za-z]:.*")) {
return path
} else {
return "${env.WORKSPACE}/${path}"
}
}
}
16 changes: 14 additions & 2 deletions src/ru/pulsar/jenkins/library/steps/InitFromFiles.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import ru.pulsar.jenkins.library.configuration.SourceFormat
import ru.pulsar.jenkins.library.ioc.ContextRegistry
import ru.pulsar.jenkins.library.utils.Logger
import ru.pulsar.jenkins.library.utils.VRunner
import ru.pulsar.jenkins.library.steps.CreateInfobase

class InitFromFiles implements Serializable {

Expand Down Expand Up @@ -41,9 +42,20 @@ class InitFromFiles implements Serializable {
srcDir = config.srcDir;
}

def createInfobase = new CreateInfobase(config)
createInfobase.run()

Logger.println("Выполнение загрузки конфигурации из файлов")
String vrunnerPath = VRunner.getVRunnerPath();
def initCommand = "$vrunnerPath init-dev --src $srcDir --ibconnection \"/F./build/ib\""
VRunner.exec(initCommand)
def command = "$vrunnerPath update-dev --src $srcDir --ibconnection \"/F./build/ib\""

def options = config.initInfoBaseOptions

String vrunnerSettings = options.vrunnerSettings
if (vrunnerSettings && steps.fileExists(vrunnerSettings)) {
command += " --settings $vrunnerSettings"
}

VRunner.exec(command)
}
}
16 changes: 15 additions & 1 deletion src/ru/pulsar/jenkins/library/steps/InitFromStorage.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import ru.pulsar.jenkins.library.utils.Logger
import ru.pulsar.jenkins.library.utils.RepoUtils
import ru.pulsar.jenkins.library.utils.VRunner
import ru.pulsar.jenkins.library.utils.VersionParser
import ru.pulsar.jenkins.library.steps.CreateInfobase

import static ru.pulsar.jenkins.library.configuration.Secrets.UNKNOWN_ID

Expand Down Expand Up @@ -43,6 +44,9 @@ class InitFromStorage implements Serializable {
String storageCredentials = secrets.storage == UNKNOWN_ID ? repoSlug + "_STORAGE_USER" : secrets.storage
String storagePath = secrets.storagePath == UNKNOWN_ID ? repoSlug + "_STORAGE_PATH" : secrets.storagePath

def createInfobase = new CreateInfobase(config)
createInfobase.run()

steps.withCredentials([
steps.usernamePassword(
storageCredentials,
Expand All @@ -54,8 +58,18 @@ class InitFromStorage implements Serializable {
'RUNNER_STORAGE_NAME'
)
]) {
Logger.println("Выполнение загрузки конфигурации из хранилища")
String vrunnerPath = VRunner.getVRunnerPath()
VRunner.exec "$vrunnerPath init-dev --storage $storageVersionParameter --ibconnection \"/F./build/ib\""
def command = "$vrunnerPath update-dev --storage $storageVersionParameter --ibconnection \"/F./build/ib\""

def options = config.initInfoBaseOptions

String vrunnerSettings = options.vrunnerSettings
if (vrunnerSettings && steps.fileExists(vrunnerSettings)) {
command += " --settings $vrunnerSettings"
}

VRunner.exec(command)
}
}

Expand Down
32 changes: 32 additions & 0 deletions src/ru/pulsar/jenkins/library/utils/FileUtils.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,36 @@ class FileUtils {
.replaceAll('\\\\', '/')
.toString()
}

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

FilePath localPathToFile = getFilePath(filePathTo)

if (isValidUrl(filePathFrom)) {
// If the path is a URL, download the file
localPathToFile.copyFrom(new URL(filePathFrom))
} else {
// If the path is a local file, copy the file
String localPath = getAbsolutePath(filePathFrom, env)
FilePath localFilePath = getFilePath(localPath)
localPathToFile.copyFrom(localFilePath)
}
}

private static boolean isValidUrl(String url) {
try {
new URL(url)
return true
} catch (MalformedURLException e) {
return false
}
}

private static String getAbsolutePath(String path, def env) {
if (path.startsWith("/") || path.startsWith("\\") || path.matches("^[A-Za-z]:.*")) {
return path
} else {
return "${env.WORKSPACE}/${path}"
}
}
}

0 comments on commit 60e184c

Please sign in to comment.