首頁 > 軟體

如何在Snap包中定義全域性的plug

2020-06-16 17:34:29

我們知道在我們snap應用中,我們可以通過定義plug來存取我們所需要的資源.在一個snap包中,我們也可以定義許多的應用,每個應用可以分別定義自己的plug.假如一個Snap包有一個plug是共同的,那麼,我們有上面辦法來定義一個全域性的plug,這樣所有的在同一個包中的所有的snap應用都可以同時擁有這個plug.這個到底怎麼做呢?

關於snap中的interface及plug概念,請參閱我之前的文章"安裝snap應用到Ubuntu 16.4桌面系統".

最近,我讀了一篇關於snap interface的文章.很受啟發.文章可以在地址找到.其中有一段非常有意思的一段話:

Note that only the links app refers to plugs, the bookmarks app does not. If a plug or slot is declared in a snap, but not associated with a specific application they will be implicitly bound to all apps. When a plug or slot is specified by one or more apps, as in the above example, it will be bound only to those applications. Compare that to the following code:

它的意思就是如果我們在我們的snapcraft.yaml中定義一個plug,但是它不被任何的應用所應用,那麼它隱含地就是所有的應用都有這個plug.

我們拿我們的例程https://github.com/liu-xiao-guo/helloworld-plug為例,我們定義如下:

name: hello-xiaoguo
version: "1.0"
architectures: [ all ]
summary: The 'hello-world' of snaps
description: |
    This is a simple snap example that includes a few interesting binaries
    to demonstrate snaps and their confinement.
    * hello-world.env  - dump the env of commands run inside app sandbox
    * hello-world.evil - show how snappy sandboxes binaries
    * hello-world.sh   - enter interactive shell that runs in app sandbox
    * hello-world      - simply output text
confinement: strict
type: app  #it can be gadget or framework

apps:
 env:
   command: bin/env
 evil:
   command: bin/evil
 sh:
   command: bin/sh
 hello-world:
   command: bin/echo
 createfile:
   command: bin/createfile
 createfiletohome:
   command: bin/createfiletohome
 writetocommon:
   command: bin/writetocommon

plugs:
    home:
        interface: home

parts:
 hello:
  plugin: copy
  files:
    ./bin: bin


在上面的snapcraft.yaml檔案中,我們寫了如下的句子:

plugs:
    home:
        interface: home


由於在我們的任何一個應用中都沒有參照home plug,所有這個plug將被定義為包級的plug,也就是說所有的app都享有這個plug.我們可以做一個簡單的測試.我們安裝好我們的hello snap後,執行如下的命令:

liuxg@liuxg:~$ hello-xiaoguo.createfiletohome 
Hello a nice World!
This example demonstrates the app confinement
This app tries to write to its own user directory
Succeeded! Please find a file created at /home/liuxg/snap/hello-xiaoguo/x1/test.txt
If do not see this, please file a bug

我們的createtohome指令碼如下:

#!/bin/sh

set -e
echo "Hello a nice World!"

echo "This example demonstrates the app confinement"
echo "This app tries to write to its own user directory"

echo "Haha" > /home/$USER/test.txt

echo "Succeeded! Please find a file created at $HOME/test.txt"
echo "If do not see this, please file a bug"


顯然它向home裡寫入一個叫做test.txt的檔案.我們的寫入操作是成功的.

從我們的檔案目錄中,我們可以看出來我們剛剛建立的檔案test.txt.細心的開發者也可以出去上面定義的plug,在試一試是否成功?


IT145.com E-mail:sddin#qq.com