Error detected while processing function SwitchFlowOrTsLsps nvim windows 10 - neovim

Hello I tried to enter a js file and upon entering I got this error:
Error detected while processing function SwitchFlowOrTsLsps:
line 4:
E121: Undefined variable: state
E15: Invalid expression: (tsserver.state == 'disabled')
Try to find the line that tells me in the different files such as maps, plugin or plugin config, the last one is the one I found it in, before I did not suffer from this error because I was only entering py, cpp and java extension files, I have the coc, but do not download anything for this, I also have the kite installed as a plugin for autocompletion
" HTML, JSX
let g:closetag_filenames = '*.html,*.js,*.jsx,*.ts,*.tsx'
" Lightlane
let g:lightline = {
\ 'active': {
\ 'left': [['mode', 'paste'], [], ['relativepath', 'modified']],
\ 'right': [['kitestatus'], ['filetype', 'percent', 'lineinfo'], ['gitbranch']]
\ },
\ 'inactive': {
\ 'left': [['inactive'], ['relativepath']],
\ 'right': [['bufnum']]
\ },
\ 'component': {
\ 'bufnum': '%n',
\ 'inactive': 'inactive'
\ },
\ 'component_function': {
\ 'gitbranch': 'fugitive#head',
\ 'cocstatus': 'coc#status'
\ },
\ 'colorscheme': 'gruvbox',
\ 'subseparator': {
\ 'left': '',
\ 'right': ''
\ }
\}
" nerdtree
let NERDTreeShowHidden=1
let NERDTreeQuitOnOpen=1
let NERDTreeAutoDeleteBuffer=1
let NERDTreeMinimalUI=1
let NERDTreeDirArrows=1
let NERDTreeShowLineNumbers=1
let NERDTreeMapOpenInTab='\t'
let g:javascript_plugin_flow = 1
" Trigger configuration. Do not use <tab> if you use https://github.com/Valloric/YouCompleteMe.
let g:UltiSnipsSnippetDirectories=[$HOME.'/config/.vim/UltiSnips']
let g:UltiSnipsExpandTrigger="<tab>"
let g:UltiSnipsJumpForwardTrigger="<tab>"
let g:UltiSnipsJumpBackwardTrigger="<S-tab>"
" deoplete
let g:deoplete#enable_at_startup = 1
let g:neosnippet#enable_completed_snippet = 1
" kite
let g:kite_supported_lenguages = ['javascript', 'python']
" coc
autocmd FileType python let b:coc_suggest_disable = 1
autocmd FileType javascript let b:coc_suggest_disable = 1
autocmd FileType scss setl iskeyword+=#-#
command! -bang -nargs=? -complete=dir GFiles
\ call fzf#vim#gitfiles(<q-args>, fzf#vim#with_preview(), <bang>0)
command! -bang -nargs=* Ag
\ call fzf#vim#ag(<q-args>, fzf#vim#with_preview(), <bang>0)
command! -bang -nargs=? -complete=dir Files
\ call fzf#vim#files(<q-args>, fzf#vim#with_preview(), <bang>0)
" if hidden is not set, TextEdit might fail.
set hidden
" Some servers have issues with backup files, see #649
set nobackup
set nowritebackup
" Better display for messages
set cmdheight=2
" You will have bad experience for diagnostic messages when it's default 4000.
set updatetime=300
" don't give |ins-completion-menu| messages.
set shortmess+=c
" always show signcolumns
set signcolumn=yes
" fugitive always vertical diffing
set diffopt+=vertical
" Use <c-space> to trigger completion.
inoremap <silent><expr> <c-space> coc#refresh()
" Remap keys for gotos
nmap <silent> gd <Plug>(coc-definition)
nmap <silent> gy <Plug>(coc-type-definition)
nmap <silent> gi <Plug>(coc-implementation)
nmap <silent> gr <Plug>(coc-references)
" Highlight symbol under cursor on CursorHold
autocmd CursorHold * silent call CocActionAsync('highlight')
autocmd BufEnter *.js :silent let myIndex = SearchPatternInFile("#flow") | call SwitchFlowOrTsLsps(myIndex)
autocmd BufEnter *.jsx :silent let myIndex = SearchPatternInFile("#flow") | call SwitchFlowOrTsLsps(myIndex)
function! SwitchFlowOrTsLsps(flowIndex)
silent let stats = CocAction("extensionStats")
silent let tsserver = get(filter(copy(stats), function('FindTsServer')), 0)
if(a:flowIndex == 0)
if(tsserver.state == 'disabled')
call CocActionAsync("toggleExtension", "coc-tsserver")
endif
else
if(tsserver.state == 'activated')
call CocActionAsync("toggleExtension", "coc-tsserver")
endif
endif
endfunction
function! FindTsServer(idx, value)
return a:value.id == 'coc-tsserver'
endfunction
let $FZF_DEFAULT_OPTS='--layout=reverse'
let g:fzf_layout = { 'window': 'call FloatingFZF()' }
function! FloatingFZF()
let buf = nvim_create_buf(v:false, v:true)
call setbufvar(buf, '&signcolumn', 'no')
let height = float2nr((&lines - 3) / 2)
let width = float2nr(&columns - (&columns * 2 / 10))
let col = float2nr((&columns - width) / 2)
let row = float2nr((&lines - height) / 2)
let opts = {
\ 'relative': 'editor',
\ 'row': row,
\ 'col': col,
\ 'width': width,
\ 'height': height
\ }
call nvim_open_win(buf, v:true, opts)
endfunction
function! SearchPatternInFile(pattern)
" Save cursor position.
let save_cursor = getcurpos()
" Set cursor position to beginning of file.
call cursor(0, 0)
" Search for the string 'hello' with a flag c. The c flag means that a
" match at the cursor position will be accepted.
let search_result = search(a:pattern, "c")
" Set the cursor back at the saved position. The setpos function was
" used here because the return value of getcurpos can be used directly
" with it, unlike the cursor function.
call setpos('.', save_cursor)
" If the search function didn't find the pattern, it will have
" returned 0, thus it wasn't found. Any other number means that an instance
" has been found.
return search_result
endfunction
How could I solve it?, thanks to all.

Can you try running this command on vim and see if it works?
:CocInstall coc-json coc-tsserver

Related

neovim's lsp does not show error messages

i have a neovim config which contains lsp configuration
on my laptop i have neovim 0.7.2 which works perfectly
but on my desktop i have neovim 0.8.0 and lsp still works but does not show error massages.
this is my config
vim.opt.tabstop = 2
vim.cmd([[colorscheme dedsec]])
vim.cmd([[set number]])
vim.cmd([[set noswapfile]])
vim.cmd([[set mouse=a]])
vim.opt.shiftwidth = 2
vim.opt.softtabstop = 2
vim.opt.expandtab = true
require("packer").startup(function(use)
-- use "wbthompson/packer.nvim"
use "vim-airline/vim-airline"
use 'vim-airline/vim-airline-themes'
use 'ryanoasis/vim-devicons'
use 'jpalardy/vim-slime'
use 'shime/vim-livedown'
use 'ap/vim-css-color'
use 'terryma/vim-multiple-cursors'
use 'mattn/emmet-vim'
use 'scrooloose/nerdtree'
use 'mxw/vim-jsx'
-- LSP
use {
'VonHeikemen/lsp-zero.nvim',
requires = {
-- LSP Support
{'neovim/nvim-lspconfig'},
{'williamboman/mason.nvim'},
{'williamboman/mason-lspconfig.nvim'},
-- Autocompletion
{'hrsh7th/nvim-cmp'},
{'hrsh7th/cmp-buffer'},
{'hrsh7th/cmp-path'},
{'saadparwaiz1/cmp_luasnip'},
{'hrsh7th/cmp-nvim-lsp'},
{'hrsh7th/cmp-nvim-lua'},
-- Snippets
{'L3MON4D3/LuaSnip'},
{'rafamadriz/friendly-snippets'},
}
}
end)
vim.cmd([[
let g:airline_powerline_fonts = 1 "Включить поддержку Powerline шрифтов
let g:airline#extensions#keymap#enabled = 0 "Не показывать текущий маппинг
let g:airline_section_z = "\ue0a1:%l/%L Col:%c" "Кастомная графа положения курсора
let g:Powerline_symbols='unicode' "Поддержка unicode
let g:airline#extensions#xkblayout#enabled = 0 "Про это позже расскажу
set guioptions= "Отключаем панели прокрутки в GUI
set showtabline=1 "Отключаем панель табов (окошки FTW)
let g:slime_target = "tmux"
let g:slime_target = "neovim"
nnoremap <leader>n :NERDTreeFocus<CR>
nnoremap <C-n> :NERDTree<CR>
nnoremap <C-b> :NERDTreeToggle<CR>
nnoremap <C-f> :NERDTreeFind<CR>
let g:user_emmet_mode='a'
set colorcolumn=109
]])
local lsp = require('lsp-zero')
lsp.preset('recommended')
lsp.nvim_workspace()
lsp.setup()
local servers = { 'pyright', 'tsserver', 'jdtls', 'rust-analyzer', 'clangd', 'sumneko_lua'}
for _, lsp in pairs(servers) do
require('lspconfig')[lsp].setup {
on_attach = on_attach,
flags = {
debounce_text_changes = 150,
}
}
end
local signs = { Error = " ", Warn = " ", Hint = " ", Info = " " }
for type, icon in pairs(signs) do
local hl = "DiagnosticSign" .. type
vim.fn.sign_define(hl, { text = icon, texthl= hl, numhl = hl })
end
this is how it works on laptop
this is how it works on my desktop
i have tried to install neovim 0.7.2 but it does not help me
i also have tired to update and reinstall plugins but it also does not help
https://github.com/VonHeikemen/lsp-zero.nvim/blob/v1.x/doc/md/lsp.md#diagnostics
simply follow this documentation.
change
virtual_text = false,
to
virtual_text = true,
if you have the same situation try to install williamboman/nvim-lsp-installer. it have halped in my situation

neovim error Windows 10 UltiSnips with python 3

I receive this error every time I try to write code in nvim, in any file it does not matter if it is not python, I just installed vim and what I did is copy a repository, I don't know which part could be wrong, also mention that the paths are /user/.vim, and that the repository that I clone for this is from a person with mac.
This is the UltiSnips.vim:
if exists("b:did_autoload_ultisnips")
finish
endif
let b:did_autoload_ultisnips = 1
" Also import vim as we expect it to be imported in many places.
py3 import vim
py3 from UltiSnips import UltiSnips_Manager
function! s:compensate_for_pum() abort
""" The CursorMovedI event is not triggered while the popup-menu is visible,
""" and it's by this event that UltiSnips updates its vim-state. The fix is
""" to explicitly check for the presence of the popup menu, and update
""" the vim-state accordingly.
if pumvisible()
py3 UltiSnips_Manager._cursor_moved()
endif
endfunction
function! UltiSnips#Edit(bang, ...) abort
if a:0 == 1 && a:1 != ''
let type = a:1
else
let type = ""
endif
py3 vim.command("let file = '%s'" % UltiSnips_Manager._file_to_edit(vim.eval("type"), vim.eval('a:bang')))
if !len(file)
return
endif
let mode = 'e'
if exists('g:UltiSnipsEditSplit')
if g:UltiSnipsEditSplit == 'vertical'
let mode = 'vs'
elseif g:UltiSnipsEditSplit == 'horizontal'
let mode = 'sp'
elseif g:UltiSnipsEditSplit == 'tabdo'
let mode = 'tabedit'
elseif g:UltiSnipsEditSplit == 'context'
let mode = 'vs'
if winwidth(0) <= 2 * (&tw ? &tw : 80)
let mode = 'sp'
endif
endif
endif
exe ':'.mode.' '.escape(file, ' ')
endfunction
function! UltiSnips#AddFiletypes(filetypes) abort
py3 UltiSnips_Manager.add_buffer_filetypes(vim.eval("a:filetypes"))
return ""
endfunction
function! UltiSnips#FileTypeComplete(arglead, cmdline, cursorpos) abort
let ret = {}
let items = map(
\ split(globpath(&runtimepath, 'syntax/*.vim'), '\n'),
\ 'fnamemodify(v:val, ":t:r")'
\ )
call insert(items, 'all')
for item in items
if !has_key(ret, item) && item =~ '^'.a:arglead
let ret[item] = 1
endif
endfor
return sort(keys(ret))
endfunction
function! UltiSnips#ExpandSnippet() abort
py3 UltiSnips_Manager.expand()
return ""
endfunction
function! UltiSnips#ExpandSnippetOrJump() abort
call s:compensate_for_pum()
py3 UltiSnips_Manager.expand_or_jump()
return ""
endfunction
function! UltiSnips#ListSnippets() abort
py3 UltiSnips_Manager.list_snippets()
return ""
endfunction
function! UltiSnips#SnippetsInCurrentScope(...) abort
let g:current_ulti_dict = {}
let all = get(a:, 1, 0)
if all
let g:current_ulti_dict_info = {}
endif
py3 UltiSnips_Manager.snippets_in_current_scope(int(vim.eval("all")))
return g:current_ulti_dict
endfunction
function! UltiSnips#SaveLastVisualSelection() range abort
py3 UltiSnips_Manager._save_last_visual_selection()
return ""
endfunction
function! UltiSnips#JumpBackwards() abort
call s:compensate_for_pum()
py3 UltiSnips_Manager.jump_backwards()
return ""
endfunction
function! UltiSnips#JumpForwards() abort
call s:compensate_for_pum()
py3 UltiSnips_Manager.jump_forwards()
return ""
endfunction
function! UltiSnips#AddSnippetWithPriority(trigger, value, description, options, filetype, priority) abort
py3 trigger = vim.eval("a:trigger")
py3 value = vim.eval("a:value")
py3 description = vim.eval("a:description")
py3 options = vim.eval("a:options")
py3 filetype = vim.eval("a:filetype")
py3 priority = vim.eval("a:priority")
py3 UltiSnips_Manager.add_snippet(trigger, value, description, options, filetype, priority)
return ""
endfunction
function! UltiSnips#Anon(value, ...) abort
" Takes the same arguments as SnippetManager.expand_anon:
" (value, trigger="", description="", options="")
py3 args = vim.eval("a:000")
py3 value = vim.eval("a:value")
py3 UltiSnips_Manager.expand_anon(value, *args)
return ""
endfunction
function! UltiSnips#CursorMoved() abort
py3 UltiSnips_Manager._cursor_moved()
endf
function! UltiSnips#LeavingBuffer() abort
let from_preview = getwinvar(winnr('#'), '&previewwindow')
let to_preview = getwinvar(winnr(), '&previewwindow')
if !(from_preview || to_preview)
py3 UltiSnips_Manager._leaving_buffer()
endif
endf
function! UltiSnips#LeavingInsertMode() abort
py3 UltiSnips_Manager._leaving_insert_mode()
endfunction
function! UltiSnips#TrackChange() abort
py3 UltiSnips_Manager._track_change()
endfunction
function! UltiSnips#RefreshSnippets() abort
py3 UltiSnips_Manager._refresh_snippets()
endfunction
" }}}
Your error is mostly because you don't have the pynvim Python package installed. Do a pip install pynvim and it should work.
Be careful because I couldn't make it work with latest version of python (3.9), as it says it needs Build Tools for C++.

NVim Omnisharp-Vim autocomplete on tab not working

Using NeoVim and autocomplete is not completing the suggestion.
For example:
I get the popup when start typing a word such as public.
I just start typing pu and then the dialogue pops up to suggest the full word, but when I hit tab is just adds a tab after the word with out completing.
Here is by init.vim if it helps
"set this to 1 to use ultisnips for snippet handling
let s:using_snippets = 0
" vim-plug: {{{
call plug#begin('~/.vim/plugged')
Plug 'omnisharp/omnisharp-vim'
" Mappings, code-actions available flag and statusline integration
Plug 'nickspoons/vim-sharpenup'
" Linting/error highlighting
Plug 'dense-analysis/ale'
" Vim FZF integration, used as OmniSharp selector
Plug 'junegunn/fzf'
Plug 'junegunn/fzf.vim'
" Code Snippets
Plug 'SirVer/ultisnips'
" Autocompletion
Plug 'prabirshrestha/asyncomplete.vim'
" Colorscheme
Plug 'gruvbox-community/gruvbox'
" Statusline
Plug 'itchyny/lightline.vim'
Plug 'shinchu/lightline-gruvbox.vim'
Plug 'maximbaz/lightline-ale'
" File Navigation
Plug 'preservim/nerdtree'
" Snippet support
if s:using_snippets
Plug 'sirver/ultisnips'
endif
call plug#end()
" }}}
"
" Line Numbers
:set number relativenumber
:augroup numbertoggle
: autocmd!
: autocmd BufEnter,FocusGained,InsertLeave * set relativenumber
: autocmd BufLeave,FocusLost,InsertEnter * set norelativenumber
:augroup END
" fuzzy file search
set runtimepath^=~/.vim/bundle/ctrlp.vim
" Settings: {{{
filetype indent plugin on
if !exists('g:syntax_on') | syntax enable | endif
set encoding=utf-8
scriptencoding utf-8
set completeopt=menuone,noinsert,noselect,preview
set backspace=indent,eol,start
set expandtab
set shiftround
set shiftwidth=4
set softtabstop=-1
set tabstop=8
set textwidth=80
set title
set hidden
set nofixendofline
set nostartofline
set splitbelow
set splitright
set hlsearch
set incsearch
set laststatus=2
set noruler
set noshowmode
set signcolumn=yes
set mouse=a
set updatetime=1000
" }}}
" Colors: {{{
augroup ColorschemePreferences
autocmd!
" These preferences clear some gruvbox background colours, allowing transparency
autocmd ColorScheme * highlight Normal ctermbg=NONE guibg=NONE
autocmd ColorScheme * highlight SignColumn ctermbg=NONE guibg=NONE
autocmd ColorScheme * highlight Todo ctermbg=NONE guibg=NONE
" Link ALE sign highlights to similar equivalents without background colours
autocmd ColorScheme * highlight link ALEErrorSign WarningMsg
autocmd ColorScheme * highlight link ALEWarningSign ModeMsg
autocmd ColorScheme * highlight link ALEInfoSign Identifier
augroup END
" Use truecolor in the terminal, when it is supported
if has('termguicolors')
set termguicolors
endif
set background=dark
colorscheme gruvbox
" }}}
" ALE: {{{
let g:ale_sign_error = '•'
let g:ale_sign_warning = '•'
let g:ale_sign_info = '·'
let g:ale_sign_style_error = '·'
let g:ale_sign_style_warning = '·'
let g:ale_linters = { 'cs': ['OmniSharp'] }
" }}}
" Asyncomplete: {{{
let g:asyncomplete_auto_popup = 1
let g:asyncomplete_auto_completeopt = 1
" }}}
" Sharpenup: {{{
" All sharpenup mappings will begin with `<Space>os`, e.g. `<Space>osgd` for
" :OmniSharpGotoDefinition
" let g:sharpenup_map_prefix = '<Space>os'
let g:sharpenup_map_prefix = ',os'
let g:sharpenup_statusline_opts = { 'Text': '%s (%p/%P)' }
let g:sharpenup_statusline_opts.Highlight = 0
augroup OmniSharpIntegrations
autocmd!
autocmd User OmniSharpProjectUpdated,OmniSharpReady call lightline#update()
augroup END
" }}}
" Lightline: {{{
let g:lightline = {
\ 'colorscheme': 'gruvbox',
\ 'active': {
\ 'right': [
\ ['linter_checking', 'linter_errors', 'linter_warnings', 'linter_infos', 'linter_ok'],
\ ['lineinfo'], ['percent'],
\ ['fileformat', 'fileencoding', 'filetype', 'sharpenup']
\ ]
\ },
\ 'inactive': {
\ 'right': [['lineinfo'], ['percent'], ['sharpenup']]
\ },
\ 'component': {
\ 'sharpenup': sharpenup#statusline#Build()
\ },
\ 'component_expand': {
\ 'linter_checking': 'lightline#ale#checking',
\ 'linter_infos': 'lightline#ale#infos',
\ 'linter_warnings': 'lightline#ale#warnings',
\ 'linter_errors': 'lightline#ale#errors',
\ 'linter_ok': 'lightline#ale#ok'
\ },
\ 'component_type': {
\ 'linter_checking': 'right',
\ 'linter_infos': 'right',
\ 'linter_warnings': 'warning',
\ 'linter_errors': 'error',
\ 'linter_ok': 'right'
\ }
\ }
" Use unicode chars for ale indicators in the statusline
let g:lightline#ale#indicator_checking = "\uf110 "
let g:lightline#ale#indicator_infos = "\uf129 "
let g:lightline#ale#indicator_warnings = "\uf071 "
let g:lightline#ale#indicator_errors = "\uf05e "
let g:lightline#ale#indicator_ok = "\uf00c "
" }}}
" OmniSharp: {{{
let g:OmniSharp_server_stdio = 1
let g:OmniSharp_translate_cygwin_wsl = 1
let g:OmniSharp_popup_position = 'peek'
if has('nvim')
let g:OmniSharp_popup_options = {
\ 'winhl': 'Normal:NormalFloat'
\}
else
let g:OmniSharp_popup_options = {
\ 'highlight': 'Normal',
\ 'padding': [0, 0, 0, 0],
\ 'border': [1]
\}
endif
let g:OmniSharp_popup_mappings = {
\ 'sigNext': '<C-n>',
\ 'sigPrev': '<C-p>',
\ 'pageDown': ['<C-f>', '<PageDown>'],
\ 'pageUp': ['<C-b>', '<PageUp>']
\}
if s:using_snippets
let g:OmniSharp_want_snippet = 1
endif
let g:OmniSharp_highlight_groups = {
\ 'ExcludedCode': 'NonText'
\}
" }}}
"
imap <c-space> <Plug>(asyncomplete_force_refresh)
inoremap <expr> <Tab> pumvisible() ? "\<C-n>" : "\<Tab>"
inoremap <expr> <S-Tab> pumvisible() ? "\<C-p>" : "\<S-Tab>"
inoremap <expr> <cr> pumvisible() ? asyncomplete#close_popup() : "\<cr>"
I was being foolish, I should have used Ctl+P or Ctl+N.
Noob.
Closing ticket

Yocto's ROOTFS_POSTPROCESS_COMMAND not working?

I'm trying to use this variable in order to remove a few unwanted init files after my root FS is generated, following the documentation at:
http://www.yoctoproject.org/docs/1.8/ref-manual/ref-manual.html#migration-1.6-variable-changes-variable-entry-behavior
I've added exactly the same snippet to my recipe (.bb) file, without any luck... what's wrong? This is the code I'm putting in my .bb file:
my_postprocess_function() {
echo "hello" > ${IMAGE_ROOTFS}/hello.txt
}
ROOTFS_POSTPROCESS_COMMAND += "my_postprocess_function; "
The logs don't show any kind of error or warning, just my_postprocess_function is not executed.
I believe there is a bug that manifests itself based on which column you put the closing curly bracket in. Initially, I could not believe that this is the behaviour, but after I tested and confirmed it, here are my results:
$ bitbake --version
BitBake Build Tool Core version 1.28.0
I'm modifying core-image-minimal.bb as follows:
FAILING CASE
SUMMARY = "G5 - A small image just capable of allowing a device to boot."
IMAGE_INSTALL = "packagegroup-core-boot ${ROOTFS_PKGMANAGE_BOOTSTRAP} ${CORE_IMAGE_EXTRA_INSTALL}"
IMAGE_LINGUAS = " "
LICENSE = "MIT"
IMAGE_ROOTFS_SIZE ?= "8192"
IMAGE_ROOTFS_EXTRA_SPACE_append = "${#bb.utils.contains("DISTRO_FEATURES", "systemd", " + 4096", "" ,d)}"
inherit core-image
my_postprocess_function() {
echo "hello" > ${IMAGE_ROOTFS}/hello.txt
}
ROOTFS_POSTPROCESS_COMMAND += "my_postprocess_function; "
The above fails silently and does not generate hello.txt
Notice how the } is indented by one space (indenting by any amount other than once space will also fail).
However, if you modify it as follows:
SUCCEEDING CASE
SUMMARY = "G5 - A small image just capable of allowing a device to boot."
IMAGE_INSTALL = "packagegroup-core-boot ${ROOTFS_PKGMANAGE_BOOTSTRAP} ${CORE_IMAGE_EXTRA_INSTALL}"
IMAGE_LINGUAS = " "
LICENSE = "MIT"
IMAGE_ROOTFS_SIZE ?= "8192"
IMAGE_ROOTFS_EXTRA_SPACE_append = "${#bb.utils.contains("DISTRO_FEATURES", "systemd", " + 4096", "" ,d)}"
inherit core-image
my_postprocess_function() {
echo "hello" > ${IMAGE_ROOTFS}/hello.txt
}
ROOTFS_POSTPROCESS_COMMAND += "my_postprocess_function; "
then, hello.txt is generated.
The way I found this bug is by moving the 'inherit core-image' line to the end of the file as follows:
DIAGNOSIS
SUMMARY = "G5 - A small image just capable of allowing a device to boot."
IMAGE_INSTALL = "packagegroup-core-boot ${ROOTFS_PKGMANAGE_BOOTSTRAP} ${CORE_IMAGE_EXTRA_INSTALL}"
IMAGE_LINGUAS = " "
LICENSE = "MIT"
IMAGE_ROOTFS_SIZE ?= "8192"
IMAGE_ROOTFS_EXTRA_SPACE_append = "${#bb.utils.contains("DISTRO_FEATURES", "systemd", " + 4096", "" ,d)}"
my_postprocess_function() {
echo "hello" > ${IMAGE_ROOTFS}/hello.txt
}
ROOTFS_POSTPROCESS_COMMAND += "my_postprocess_function; "
inherit core-image
In which case, I got the error:
ERROR: ParseError at ......./recipes-core/images/core-image-minimal.bb:13: Shell function my_postprocess_function is never closed
I mentioned this last part in case anyone else is having weird behaviour and you have exhausted all debugging possibilities.
cyberguijarro only says that his code exists in a .bb recipe but didn't say if that recipe was an image recipe or not.
Since he didn't accept any of the given answers, I'll suggest that his issue was that his code was not in an image recipe.
This is working for me:
my_postprocess_function() {
echo "hello" > ${IMAGE_ROOTFS}/hello.txt
}
ROOTFS_POSTPROCESS_COMMAND_append = " \
my_postprocess_function; \
"

Classic ASP amazon s3 rest authorisation

I am confused on what I am doing wrong here...
<script language="javascript" runat="server">
function GMTNow(){return new Date().toGMTString()}
</script>
<%
Const AWS_BUCKETNAME = "uk-bucketname"
Const AWS_ACCESSKEY = "GOES HERE"
Const AWS_SECRETKEY = "SECRET"
LocalFile = Server.Mappath("/test.jpg")
Dim sRemoteFilePath
sRemoteFilePath = "/files/test.jpg" 'Remote Path, note that AWS paths (in fact they aren't real paths) are strictly case sensitive
Dim strNow
strNow = GMTNow() ' GMT Date String
Dim StringToSign
StringToSign = Replace("PUT\n\nimage/jpeg\n\nx-amz-date:" & strNow & "\n/"& AWS_BUCKETNAME & sRemoteFilePath, "\n", vbLf)
Dim Signature
Signature = BytesToBase64(HMACSHA1(AWS_SECRETKEY, StringToSign))
Dim Authorization
Authorization = "AWS " & AWS_ACCESSKEY & ":" & Signature
Dim AWSBucketUrl
AWSBucketUrl = "http://s3.amazonaws.com/" & AWS_BUCKETNAME
With Server.CreateObject("Microsoft.XMLHTTP")
.open "PUT", AWSBucketUrl & sRemoteFilePath, False
.setRequestHeader "Authorization", Authorization
.setRequestHeader "Content-Type", "image/jpeg"
.setRequestHeader "Host", AWS_BUCKETNAME & ".s3.amazonaws.com"
.setRequestHeader "x-amz-date", strNow
.send GetBytes(LocalFile) 'Get bytes of local file and send
If .status = 200 Then ' successful
Response.Write "<a href="& AWSBucketUrl & sRemoteFilePath &" target=_blank>Uploaded File</a>"
Else ' an error ocurred, consider xml string of error details
Response.ContentType = "text/xml"
Response.Write .responseText
End If
End With
Function GetBytes(sPath)
dim fs,f
set fs=Server.CreateObject("Scripting.FileSystemObject")
set f=fs.GetFile(sPath)
GetBytes = f.Size
set f=nothing
set fs=nothing
End Function
Function BytesToBase64(varBytes)
With Server.CreateObject("MSXML2.DomDocument").CreateElement("b64")
.dataType = "bin.base64"
.nodeTypedValue = varBytes
BytesToBase64 = .Text
End With
End Function
Function HMACSHA1(varKey, varValue)
With Server.CreateObject("System.Security.Cryptography.HMACSHA1")
.Key = UTF8Bytes(varKey)
HMACSHA1 = .ComputeHash_2(UTF8Bytes(varValue))
End With
End Function
Function UTF8Bytes(varStr)
With Server.CreateObject("System.Text.UTF8Encoding")
UTF8Bytes = .GetBytes_4(varStr)
End With
End Function
%>
Now getting the error.
msxml3.dll error '800c0008'
The download of the specified resource has failed.
/s3.asp, line 39
I'd like to explain how S3 Rest Api works as far as I know.First, you need to learn what should be the string to sign Amazon accepts.
Format :
StringToSign = HTTP-Verb + "\n" +
Content-MD5 + "\n" +
Content-Type + "\n" +
Date + "\n" +
CanonicalizedAmzHeaders +
CanonicalizedResource;
Generating signed string :
Signature = Base64( HMAC-SHA1( YourSecretAccessKeyID, UTF-8-Encoding-Of( StringToSign ) ) );
Passing authorization header:
Authorization = "AWS" + " " + AWSAccessKeyId + ":" + Signature;
Unfortunately you'll play byte to byte since there is no any SDK released for classic asp. So, should understand by reading the entire page http://docs.amazonwebservices.com/AmazonS3/latest/dev/RESTAuthentication.html
For string to sign as you can see above in format, there are three native headers are reserved by the API. Content-Type, Content-MD5 and Date. These headers must be exists in the string to sign even your request hasn't them as empty without header name, just its value. There is an exception, Date header must be empty in string to sign if x-amz-date header is already exists in the request. Then, If request has canonical amazon headers, you should add them as key-value pairs like x-amz-headername:value. But, there is another exception need to be considered for multiple headers. Multiple headers should combine to one header with values comma separated.
Correct
x-amz-headername:value1,value2
Wrong
x-amz-headername:value1\n
x-amz-headername:value2
Most importantly, headers must be ascending order by its group in the string to sign. First, reserved headers with ascending order, then canonical headers with ascending order.
I'd recommend using DomDocument functionality to generate Base64 encoded strings.
Additionally instead of a Windows Scripting Component (.wsc files), you could use .Net's interops such as System.Security.Cryptography to generating keyed hashes more effectively with power of System.Text. All of these interoperabilities are available in today's IIS web servers.
So, as an example I wrote the below script just sends a file to bucket you specified. Consider and test it.
Assumed local file name is myimage.jpg and will be uploaded with same name to root of the bucket.
<script language="javascript" runat="server">
function GMTNow(){return new Date().toGMTString()}
</script>
<%
Const AWS_BUCKETNAME = "uk-bucketname"
Const AWS_ACCESSKEY = "GOES HERE"
Const AWS_SECRETKEY = "SECRET"
LocalFile = Server.Mappath("/test.jpg")
Dim sRemoteFilePath
sRemoteFilePath = "/files/test.jpg" 'Remote Path, note that AWS paths (in fact they aren't real paths) are strictly case sensitive
Dim strNow
strNow = GMTNow() ' GMT Date String
Dim StringToSign
StringToSign = Replace("PUT\n\nimage/jpeg\n\nx-amz-date:" & strNow & "\n/"& AWS_BUCKETNAME & sRemoteFilePath, "\n", vbLf)
Dim Signature
Signature = BytesToBase64(HMACSHA1(AWS_SECRETKEY, StringToSign))
Dim Authorization
Authorization = "AWS " & AWS_ACCESSKEY & ":" & Signature
Dim AWSBucketUrl
AWSBucketUrl = "https://" & AWS_BUCKETNAME & ".s3.amazonaws.com"
With Server.CreateObject("MSXML2.ServerXMLHTTP.6.0")
.open "PUT", AWSBucketUrl & sRemoteFilePath, False
.setRequestHeader "Authorization", Authorization
.setRequestHeader "Content-Type", "image/jpeg"
.setRequestHeader "Host", AWS_BUCKETNAME & ".s3.amazonaws.com"
.setRequestHeader "x-amz-date", strNow
.send GetBytes(LocalFile) 'Get bytes of local file and send
If .status = 200 Then ' successful
Response.Write "<a href="& AWSBucketUrl & sRemoteFilePath &" target=_blank>Uploaded File</a>"
Else ' an error ocurred, consider xml string of error details
Response.ContentType = "text/xml"
Response.Write .responseText
End If
End With
Function GetBytes(sPath)
With Server.CreateObject("Adodb.Stream")
.Type = 1 ' adTypeBinary
.Open
.LoadFromFile sPath
.Position = 0
GetBytes = .Read
.Close
End With
End Function
Function BytesToBase64(varBytes)
With Server.CreateObject("MSXML2.DomDocument").CreateElement("b64")
.dataType = "bin.base64"
.nodeTypedValue = varBytes
BytesToBase64 = .Text
End With
End Function
Function HMACSHA1(varKey, varValue)
With Server.CreateObject("System.Security.Cryptography.HMACSHA1")
.Key = UTF8Bytes(varKey)
HMACSHA1 = .ComputeHash_2(UTF8Bytes(varValue))
End With
End Function
Function UTF8Bytes(varStr)
With Server.CreateObject("System.Text.UTF8Encoding")
UTF8Bytes = .GetBytes_4(varStr)
End With
End Function
%>
The Amazon Signature must be url encoded in a slightly different way to what VBSCript encodes. The following function will encode the result correctly:
JScript Version:
function amazonEncode(s)
{
return Server.UrlEncode(s).replace(/\+/g,"%20").replace(/\%2E/g,".").replace(/\%2D/g,"-").replace(/\%7E/g,"~").replace(/\%5F/g,"_");
}
VBScript Version:
function amazonEncode(s)
dim retval
retval = Server.UrlEncode(s)
retval = replace(retval,"+","%20")
retval = replace(retval,"%2E",".")
retval = replace(retval,"%2D","-")
retval = replace(retval,"%7E","~")
retval = replace(retval,"%5F","_")
amazonEncode = retval
end function
As for base64, I used .NET's already built functionality for it. I had to create a DLL to wrap it, so that I could use it from JScript (or VBScript).
Here's how to create that dll:
Download the free C# 2010 Express and install it.
You also need to use two other tools that you won’t have a path to, so you will need to add the path to your PATH environment variable, so at a cmd prompt search for regasm.exe, guidgen.exe and sn.exe (you might find several versions – select the one with the latest date).
• cd\
• dir/s regasm.exe
• dir/s sn.exe
• dir/s guidgen.exe
So as an example, a COM object that has just one method which just returns “Hello”:
Our eventual aim is to use it like this:
<%#Language=JScript%>
<%
var x = Server.CreateObject("blah.whatever");
Response.Write(x.someMethod());
%>
or
<%#Language=VBScript%>
<%
dim x
set x = Server.CreateObject("blah.whatever")
Response.Write x.someMethod()
%>
• Start C# and create a new project
• Select “Empty Project”
• Give it a name – this becomes the namespace by default (the blah in the sample above)
• Next save the project (so you know where to go for the next bit). This will create a folder structure like so:
o blah this contains your solution files that the editor needs (blah.sln etc)
 blah this contains your source code and project files
• bin
o Debug the compiled output ends up here
• Next, using the cmd console, navigate to the root blah folder and create a key pair file:
sn –k key.snk
• Next you need a unique guid (enter guidgen at the cmd prompt)
o Select registry format
o Click “New Guid”
o Click “Copy”
• Back to C# editor – from the menu, select Project – Add Class
• Give it a name – this is the whatever in the sample above
• After the opening brace just after the namespace line type:
[GuidAttribute(“paste your guid here”)]
remove the curly brackets from your pasted guid
• You will need to add another “using” at the top
using System.Runtime.InteropServices;
• Finally you need to create someMethod
The final C# code looks like this (the bits in red may be different in your version):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace blah
{
[GuidAttribute("AEF4F27F-9E97-4189-9AD5-64386A1699A7")]
public class whatever
{
public string someMethod()
{
return "Hello";
}
}
}
• Next, from the menu, select Project – Properties
o On the left, select Application and, for the Output type dropdown, select “Class Library”
o On the left, select Signing and tick the “Sign the assembly” box, then browse to the key.snk file you made earlier
o Save the properties (CTRL-S)
• Next build the dll (Press F6) – This will create a dll in the Debug folder
• Open a cmd window as administrator (right click cmd.exe and select “Run as Administrator”)
• Navigate to the Debug folder and enter the following to register the assembly:
regasm blah.dll /tlb:blah.tlb /codebase blah
That’s it – the above is a genuine COM component and will work in other applications, the example below allows for event handling and only really works in ASP due to the default property mechanism of ASP:
The code for the base64 stuff would be:
// returns a base 64 encoded string that has been encrypted with SHA256
// parameters:
// s string to encrypt
// k key to use during encryption
public string getBase64SHA256(string s, string k)
{
HMACSHA256 sha = new HMACSHA256();
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
sha.Key = encoding.GetBytes(k);
byte[] hashBytes = sha.ComputeHash(encoding.GetBytes(s));
return System.Convert.ToBase64String(hashBytes);
}
// returns a base 64 encoded string that has been encrypted with SHA1
// parameters:
// s string to encrypt
// k key to use during encryption
public string getBase64SHA1(string s, string k)
{
HMACSHA1 sha = new HMACSHA1();
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
sha.Key = encoding.GetBytes(k);
byte[] hashBytes = sha.ComputeHash(encoding.GetBytes(s));
return System.Convert.ToBase64String(hashBytes);
}
You would need the relevant usings:
using System.Security.Cryptography;
The signature in full must have all the query string name-value pairs in alphabetical order before computing the SHA and base64. Here is my version of the signature creator function:
function buildAmazonSignature(host,req,qstring)
{
var str="", i, arr = String(qstring).split("&");
for (i=0; i<arr.length; i++)
arr[i] = arr[i].split("=");
arr.sort(amazonSortFunc);
for (i=0; i<arr.length; i++)
{
if (str != "")
str += "&";
str += arr[i][0] + "=" + arr[i][1];
}
str = "GET\n"+host+"\n"+req+"\n"+str;
var utils = Server.CreateObject("FMAG.Utils");
var b64 = utils.getBase64SHA256(str, "xxxxxxxxxx");
utils = null;
return amazonEncode(b64);
}
function amazonSortFunc(a,b)
{
return (a[0]<b[0])?-1:((a[0]>b[0])?1:0);
}
VBScript doesn't have a very good array sort facility, so you'll have to work that one out yourself - sorry
Also I have the timestamp in this format:
YYYY-MM-DDTHH:MM:SSZ
Also the stuff in the query string included the following:
AWSAccessKeyId
SignatureMethod
SignatureVersion
Version
Expires
Action
Hope that helps
Thank you so much for this question, it has been such a great help to start my WSH/VBScript for my S3 backup service ;-)
I do not have much time, so I will not go through the details of the things I have changed from Chris' code, but please find below my little prototype script which works perfectly ;-)
This is just a WSH/VBScript, so you do not need IIS to run it, you just need to paste the content in a file with the ".vbs" extension, and you can then directly execute it ;-)
Option Explicit
'-- Amazon Web Services > My Account > Access Credentials > Access Keys --'
Dim strAccessKeyID: strAccessKeyID = "..."
Dim strSecretAccessKey: strSecretAccessKey = "..."
'-- Parameters: --'
Dim strLocalFile: strLocalFile = "..."
Dim strRemoteFile: strRemoteFile = "..."
Dim strBucket: strBucket = "..."
'-- Authentication: --'
Dim strNowInGMT: strNowInGMT = NowInGMT()
Dim strStringToSign: strStringToSign = _
"PUT" & vbLf & _
"" & vbLf & _
"text/xml" & vbLf & _
strNowInGMT & vbLf & _
"/" & strBucket + "/" & strRemoteFile
Dim strSignature: strSignature = ConvertBytesToBase64(HMACSHA1(strSecretAccessKey, strStringToSign))
Dim strAuthorization: strAuthorization = "AWS " & strAccessKeyID & ":" & strSignature
'-- Upload: --'
Dim xhttp: Set xhttp = CreateObject("MSXML2.ServerXMLHTTP")
xhttp.open "PUT", "http://" & strBucket & ".s3.amazonaws.com/" & strRemoteFile, False
xhttp.setRequestHeader "Content-Type", "text/xml"
xhttp.setRequestHeader "Date", strNowInGMT 'Yes, this line is mandatory ;-) --'
xhttp.setRequestHeader "Authorization", strAuthorization
xhttp.send GetBytesFromFile(strLocalFile)
If xhttp.status = "200" Then
WScript.Echo "The file has been successfully uploaded ;-)"
Else
WScript.Echo "There was an error :-(" & vbCrLf & vbCrLf & _
xhttp.responseText
End If
Set xhttp = Nothing
'-- NowInGMT ------------------------------------------------------------------'
Function NowInGMT()
'This is probably not the best implementation, but it works ;-) --'
Dim sh: Set sh = WScript.CreateObject("WScript.Shell")
Dim iOffset: iOffset = sh.RegRead("HKLM\System\CurrentControlSet\Control\TimeZoneInformation\ActiveTimeBias")
Dim dtNowGMT: dtNowGMT = DateAdd("n", iOffset, Now())
Dim strDay: strDay = "NA"
Select Case Weekday(dtNowGMT)
Case 1 strDay = "Sun"
Case 2 strDay = "Mon"
Case 3 strDay = "Tue"
Case 4 strDay = "Wed"
Case 5 strDay = "Thu"
Case 6 strDay = "Fri"
Case 7 strDay = "Sat"
Case Else strDay = "Error"
End Select
Dim strMonth: strMonth = "NA"
Select Case Month(dtNowGMT)
Case 1 strMonth = "Jan"
Case 2 strMonth = "Feb"
Case 3 strMonth = "Mar"
Case 4 strMonth = "Apr"
Case 5 strMonth = "May"
Case 6 strMonth = "Jun"
Case 7 strMonth = "Jul"
Case 8 strMonth = "Aug"
Case 9 strMonth = "Sep"
Case 10 strMonth = "Oct"
Case 11 strMonth = "Nov"
Case 12 strMonth = "Dec"
Case Else strMonth = "Error"
End Select
Dim strHour: strHour = CStr(Hour(dtNowGMT))
If Len(strHour) = 1 Then strHour = "0" & strHour End If
Dim strMinute: strMinute = CStr(Minute(dtNowGMT))
If Len(strMinute) = 1 Then strMinute = "0" & strMinute End If
Dim strSecond: strSecond = CStr(Second(dtNowGMT))
If Len(strSecond) = 1 Then strSecond = "0" & strSecond End If
Dim strNowInGMT: strNowInGMT = _
strDay & _
", " & _
Day(dtNowGMT) & _
" " & _
strMonth & _
" " & _
Year(dtNowGMT) & _
" " & _
strHour & _
":" & _
strMinute & _
":" & _
strSecond & _
" +0000"
NowInGMT = strNowInGMT
End Function
'-- GetBytesFromString --------------------------------------------------------'
Function GetBytesFromString(strValue)
Dim stm: Set stm = CreateObject("ADODB.Stream")
stm.Open
stm.Type = 2
stm.Charset = "ascii"
stm.WriteText strValue
stm.Position = 0
stm.Type = 1
GetBytesFromString = stm.Read
Set stm = Nothing
End Function
'-- HMACSHA1 ------------------------------------------------------------------'
Function HMACSHA1(strKey, strValue)
Dim sha1: Set sha1 = CreateObject("System.Security.Cryptography.HMACSHA1")
sha1.key = GetBytesFromString(strKey)
HMACSHA1 = sha1.ComputeHash_2(GetBytesFromString(strValue))
Set sha1 = Nothing
End Function
'-- ConvertBytesToBase64 ------------------------------------------------------'
Function ConvertBytesToBase64(byteValue)
Dim dom: Set dom = CreateObject("MSXML2.DomDocument")
Dim elm: Set elm = dom.CreateElement("b64")
elm.dataType = "bin.base64"
elm.nodeTypedValue = byteValue
ConvertBytesToBase64 = elm.Text
Set elm = Nothing
Set dom = Nothing
End Function
'-- GetBytesFromFile ----------------------------------------------------------'
Function GetBytesFromFile(strFileName)
Dim stm: Set stm = CreateObject("ADODB.Stream")
stm.Type = 1 'adTypeBinary --'
stm.Open
stm.LoadFromFile strFileName
stm.Position = 0
GetBytesFromFile = stm.Read
stm.Close
Set stm = Nothing
End Function
Dear stone-edge-technology-VBScript-mates (*), let me know if it is working for you as well ;-)
(*) This is a reference to the comment from Spudley, see above ;-)