dentimoer_setup/
lib.rs

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
use std::process::Command;
use std::fs;
use std::io;
use std::path::Path;
use regex::Regex;

pub fn install_essential_equipments() {
    let choco_install_cmd = "Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))"; // 나중에 필요하거나 코드 바뀌면 그냥 이거 고치면 됨.
    
    let opencv_include_paths = "C:\\tools\\opencv\\build\\include";
    let opencv_world_version = get_opencv_num_and_version_test();
    let opencv_link_paths = "C:\\tools\\opencv\\x64\\vc16\\lib";
    let opencv_bin_paths = "C:\\tools\\opencv\\build\\x64\\vc16\\bin";

    let one = call_admin_powershell("ls").unwrap();
    let two = call_admin_powershell("dir").unwrap();

    let mut detec: u32 = one;

    if detec == one {
        one;
        detec = two;
    }

    if detec == two {
        two;
        println!("hello world");
    }
    //call_admin_powershell("choco install llvm opencv").unwrap();
}

pub fn call_admin_powershell(cmd: &str) -> io::Result<u32> {
    let a: u32 = 0;
    let start_install = Command::new("powershell")
        .arg("-Command")
        //.arg("Start-Process PowerShell -Verb RunAs")
        .arg(format!("Start-Process PowerShell -ArgumentList '-NoExit', '-Command', '{}' -Verb RunAs", cmd))
        .output()?;

    // 명령 실행 결과 출력
    if start_install.status.success() {
        println!("PowerShell opened in developer mode.");
    } else {
        eprintln!("Failed to open PowerShell.");
    }
    Ok(a)
}

pub fn get_opencv_num_and_version_test() -> Option<u32> {
    let opencv_lib_path = "C:\\tools\\opencv\\build\\x64\\lib"; // OpenCV 라이브러리 경로
    let opencv_world_prefix = "opencv_world";

    // 라이브러리 경로가 존재하는지 확인
    if !Path::new(opencv_lib_path).exists() {
        eprintln!("OpenCV 라이브러리 경로가 존재하지 않습니다: {}", opencv_lib_path);
        return None;
    }

    // 디렉토리에서 파일 목록 읽기
    match fs::read_dir(opencv_lib_path) {
        Ok(entries) => {
            // opencv_world 뒤의 숫자를 찾기 위한 정규식
            let re = Regex::new(&format!(r"{}(\d+)\.lib", opencv_world_prefix)).unwrap();

            for entry in entries {
                if let Ok(entry) = entry {
                    let file_name = entry.file_name();
                    let file_name = file_name.to_string_lossy();

                    // 정규식에 매칭되는 파일 찾기
                    if let Some(captures) = re.captures(&file_name) {
                        if let Some(version_str) = captures.get(1) {
                            if let Ok(version) = version_str.as_str().parse::<u32>() {
                                println!("발견된 OpenCV 라이브러리: {}", file_name);
                                println!("추출된 버전 숫자: {}", version);
                                return Some(version); // 버전을 u16 값으로 반환
                            } else {
                                eprintln!("버전 숫자가 u16 형식으로 변환되지 않습니다.");
                                return None;
                            }
                        }
                    }
                }
            }

            println!("opencv_world 라이브러리를 찾을 수 없습니다.");
            None
        }
        Err(e) => {
            eprintln!("디렉토리를 읽을 수 없습니다: {}", e);
            None
        }
    }
}

pub fn set_opencv_env_test(opencv_version: u32) { // for windows 11
    let opencv_include_paths = "C:\\tools\\opencv\\build\\include";
    let opencv_link_string = format!("opencv_world{}", opencv_version);
    let opencv_link_libs = opencv_link_string.as_str();
    let opencv_link_paths = "C:\\tools\\opencv\\build\\x64\\lib";
    let opencv_bin_paths = "C:\\tools\\opencv\\build\\x64\\vc16\\bin";

    // 명령어를 실행하기 위한 PowerShell 스크립트 생성
    let script = format!(
        r#"
        [Environment]::SetEnvironmentVariable('OPENCV_INCLUDE_PATHS', '{0}', [EnvironmentVariableTarget]::Machine)
        [Environment]::SetEnvironmentVariable('OPENCV_LINK_LIBS', '{1}', [EnvironmentVariableTarget]::Machine)
        [Environment]::SetEnvironmentVariable('OPENCV_LINK_PATHS', '{2}', [EnvironmentVariableTarget]::Machine)
        $currentPath = [Environment]::GetEnvironmentVariable('Path', [EnvironmentVariableTarget]::Machine)
        if (-not ($currentPath -like '*{3}*')) {{
            [Environment]::SetEnvironmentVariable('Path', \"$currentPath;{3}\", [EnvironmentVariableTarget]::Machine)
        }}
        "#,
        opencv_include_paths, opencv_link_libs, opencv_link_paths, opencv_bin_paths
    );

    // PowerShell 명령 실행
    let output = Command::new("powershell")
        .args(["-Command", &script])
        .output()
        .expect("Failed to execute PowerShell command");

    // 결과 출력
    if output.status.success() {
        println!("환경 변수가 성공적으로 설정되었습니다.");
    } else {
        eprintln!(
            "오류 발생: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }
}